Java json 将值附加到 json 数组

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


我有以下值的现有 json 数组


{

  "test": [

    1,

    2,

    3,

    4

  ]

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


{

  "test": [

    0,  

    1,

    2,

    3,

    4

  ]


哔哔one
浏览 221回答 1
1回答

catspeake

使用 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 {&nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; ObjectMapper om = new ObjectMapper();&nbsp; &nbsp; String json = "{\r\n" +&nbsp;&nbsp; &nbsp; "&nbsp; \"test\": [\r\n" +&nbsp;&nbsp; &nbsp; "&nbsp; &nbsp; 1,\r\n" +&nbsp;&nbsp; &nbsp; "&nbsp; &nbsp; 2,\r\n" +&nbsp;&nbsp; &nbsp; "&nbsp; &nbsp; 3,\r\n" +&nbsp;&nbsp; &nbsp; "&nbsp; &nbsp; 4\r\n" +&nbsp;&nbsp; &nbsp; "&nbsp; ]\r\n" +&nbsp;&nbsp; &nbsp; "} ";&nbsp; &nbsp; System.out.println("json="+json);&nbsp; &nbsp; Wrap val = om.readValue( json, Wrap.class);&nbsp; &nbsp; System.out.println("read val="+val);&nbsp; &nbsp; val.test.add(0);&nbsp; &nbsp; Collections.sort(val.test);&nbsp; &nbsp; System.out.println("val="+val);&nbsp; &nbsp; om.enable(SerializationFeature.INDENT_OUTPUT);&nbsp; &nbsp; String json2 = om.writeValueAsString(val);&nbsp; &nbsp; System.out.println("json2="+json2);&nbsp; }}class Wrap {&nbsp; public List<Integer> test;&nbsp; @Override&nbsp; public String toString() {&nbsp; &nbsp; return "Wrap[test=" + test + "]";&nbsp; }}你得到..json={&nbsp; "test": [&nbsp; &nbsp; 1,&nbsp; &nbsp; 2,&nbsp; &nbsp; 3,&nbsp; &nbsp; 4&nbsp; ]}&nbsp;read val=Wrap[test=[1, 2, 3, 4]]val=Wrap[test=[0, 1, 2, 3, 4]]json2={&nbsp; "test" : [ 0, 1, 2, 3, 4 ]}(在 Maven 项目中编译,包括jackson-coreand jackson-databind)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java