Java json 将值附加到 json 数组

Java json append value to a json array

如何将值附加到现有 json 数组?

我现有的 json 数组具有以下值

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

我想将“0”添加到 json 数组中,以便新的 json 数组看起来像

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

使用Java和Jackson库,可以将(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 ]
}

(编译到包含jackson-corejackson-databind的Maven项目中)