爪哇JSON追加值JSON数组

问题描述 投票:0回答:1

我怎么附加价值的现有JSON阵列?

我已用现有值低于JSON数组

{
  "test": [
    1,
    2,
    3,
    4
  ]
} 

我想在加“0”到JSON阵列,使新的JSON数组会是什么样子

{
  "test": [
    0,  
    1,
    2,
    3,
    4
  ]
} 
java json jsonpath
1个回答
1
投票

使用Java和杰克逊库,你可以反序列化(JSON)字符串到Java对象,添加条目,然后序列化修改的对象(打印到JSON格式)。

在示例中,与此代码

package json;
import java.util.Collections;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class UseJson {
  public static void main(String[] args) throws Exception {
    ObjectMapper om = new ObjectMapper();
    String json = "{\r\n" + 
    "  \"test\": [\r\n" + 
    "    1,\r\n" + 
    "    2,\r\n" + 
    "    3,\r\n" + 
    "    4\r\n" + 
    "  ]\r\n" + 
    "} ";
    System.out.println("json="+json);
    Wrap val = om.readValue( json, Wrap.class);
    System.out.println("read val="+val);
    val.test.add(0);
    Collections.sort(val.test);
    System.out.println("val="+val);
    om.enable(SerializationFeature.INDENT_OUTPUT);
    String json2 = om.writeValueAsString(val);
    System.out.println("json2="+json2);
  }
}

class Wrap {
  public List<Integer> test;
  @Override
  public String toString() {
    return "Wrap[test=" + test + "]";
  }
}

你得到..

json={
  "test": [
    1,
    2,
    3,
    4
  ]
} 
read val=Wrap[test=[1, 2, 3, 4]]
val=Wrap[test=[0, 1, 2, 3, 4]]
json2={
  "test" : [ 0, 1, 2, 3, 4 ]
}

(在Maven项目进行编译,包括jackson-corejackson-databind

© www.soinside.com 2019 - 2024. All rights reserved.