gpt4 book ai didi

java - 将对象添加到 json 文件中对象的 JsonArray

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:58 25 4
gpt4 key购买 nike

这是我的 JSON 负载,我需要向 firstArray 添加更多对象。

{
"firstArray": [{
"data1": 1,
"data2": "DATA"
}, {
"data1": 2,
"data2": "DATA2"
}],
"secondArray": [{
"number": 1,
"data": "DATA3",
}, {
"number": 2,
"data": "DATA4"
}],
"thirdArray": [{
"something": 1,
"thatthing": "DATA5"
}, {
"something": 2,
"thatthing": "DATA6"
}]
}

这是我读取上述有效负载的方法:

public FirstArray createFirstArray(FirstArray object) {
try {
JsonNode jsonNode = mapper.readTree(new File(filePath));
ObjectNode objectNode = mapper.getNodeFactory().objectNode();
objectNode.putPOJO("firstArray", jsonNode.get("firstArray"));
objectNode.put("data1", object.getData1());
objectNode.put("data2", object.getData2());

System.out.println(objectNode.toString());
} catch (IOException e) {
e.printStackTrace();
}
}

它返回:

{
"firstArray":[
{
"data1":1,
"data2":"DATA"
},
{
"data1":2 "data2":"DATA2"
}
],
"data1":123,
"data2":"randomDATA"
}

我需要获取数组内的数据,因为最后一个对象不是单独的,我该怎么做?

最佳答案

您需要存储根节点。在您的示例中打印 jsonNode 变量。下面的示例执行相同的操作:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;

public class Json {

public static void main(String[] args) throws Exception {
File jsonFile = new File("test.json");

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

ObjectNode root = (ObjectNode) mapper.readTree(jsonFile);

// create new node item
ObjectNode newNode = new ObjectNode(mapper.getNodeFactory());
newNode.put("data1", 3);
newNode.put("data2", "DATA3");

// create new class item
FirstItem newItem = new FirstItem(4, "DATA4");

// get array node
ArrayNode firstArray = (ArrayNode) root.get("firstArray");

// add new ObjectNode
firstArray.add(newNode);

// add new POJO
firstArray.add(mapper.convertValue(newItem, JsonNode.class));

// serialise root
System.out.println(mapper.writeValueAsString(root));
}
}

class FirstItem {

private int data1;
private String data2;

public FirstItem(int data1, String data2) {
this.data1 = data1;
this.data2 = data2;
}

public int getData1() {
return data1;
}

public String getData2() {
return data2;
}
}

上面的代码打印:

{
"firstArray" : [ {
"data1" : 1,
"data2" : "DATA"
}, {
"data1" : 2,
"data2" : "DATA2"
}, {
"data1" : 3,
"data2" : "DATA3"
}, {
"data1" : 4,
"data2" : "DATA4"
} ],
"secondArray" : [ {
"number" : 1,
"data" : "DATA3"
}, {
"number" : 2,
"data" : "DATA4"
} ],
"thirdArray" : [ {
"something" : 1,
"thatthing" : "DATA5"
}, {
"something" : 2,
"thatthing" : "DATA6"
} ]
}

关于java - 将对象添加到 json 文件中对象的 JsonArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54908313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com