我试图通过指定该数组的路径来弄清楚如何更改JSON数组中的现有对象。
问题是我不知道如何指定数组的路径以便可以更改它。我尝试过的每种方法都没有关于如何更改ObjectNode中的数组的示例。
这是我现在的代码,在其中我尝试通过指针表示法指定数组的路径来获取和更改数组,但是,这总是不返回数组:
构建POJO类不是一种选择。
我的json结构中的数组如下:
{
RESULTS: {
ATTACHMENTS: {
ATTACHMENT: [{object}]
}
}
}
代码:
private JsonNode attachmentConversion(JsonNode object){
final String ATTACHMENT_POINTER = "/RESULTS/ATTACHMENTS/ATTACHMENT"; //Path to the array
ObjectNode OUTPUT = object.deepCopy();
OUTPUT.remove("DETAILS");
//Validate is an array - It properly fetches the array
if(object.at(ATTACHMENT_POINTER).isArray()){
int counter=0;
//Loop through attachment array - It properly fethes each object in the array
for(final JsonNode objNode : object.at(ATTACHMENT_POINTER)){
ObjectNode objectNode = objNode.deepCopy();
OUTPUT.withArray(ATTACHMENT_POINTER) //HERE IS THE PROBLEM - How do I specify the path to the array I want to replace with a new object in the withArray api? This always returns back as an empty array, even though the loop above properly fetches the array elements.
.set(counter
, objectNode
.replace("ATTACH_CONTENT"
, xmlToJson.parseXmlToJson(objNode.get("ATTACH_CONTENT")
.asText())));
counter = counter+1;
}
}
return new ObjectMapper()
.createObjectNode()
.set("customertopology", OUTPUT);
}
答案 0 :(得分:4)
我认为你不想改变传递给方法的对象,所以你做了一个深层复制。并且您想要返回一个新的JSON对象。
到目前为止我是对的吗?如果是,那么当您使用深层副本时,请使用它,遍历您关注的数组的每个元素,并将Node值替换为您想要的值。
private static JsonNode attachmentConversion(JsonNode object){
final String ATTACHMENT_POINTER = "/RESULTS/ATTACHMENTS/ATTACHMENT"; //Path to the array
ObjectNode OUTPUT = object.deepCopy();
OUTPUT.remove("DETAILS");
//Validate is an array - It properly fetches the array
if(OUTPUT.at(ATTACHMENT_POINTER).isArray()){
int counter=0;
//Loop through attachment array - It properly fethes each object in the array
for(final JsonNode objNode : OUTPUT.at(ATTACHMENT_POINTER)){
((ObjectNode)objNode).replace("ATTACH_CONTENT", xmlToJson.parseXmlToJson(objNode.get("ATTACH_CONTENT"));
}
}
return new ObjectMapper()
.createObjectNode()
.set("customertopology", OUTPUT);
}
答案 1 :(得分:2)
您可以执行
,而不是提供整个路径let topViewLabelConstraints: [NSLayoutConstraint] = [
NSLayoutConstraint(item: topViewLabel, attribute: .centerX, relatedBy: .equal, toItem: redView, attribute: .centerX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: topViewLabel, attribute: .centerY, relatedBy: .equal, toItem: redView, attribute: .centerY, multiplier: 1, constant: 0)
]
redView.addConstraints(topViewLabelConstraints)
这应该返回数组。使用fasterxml的完整代码
OUTPUT.get("RESULTS").get("ATTACHMENTS").get("ATTACHMENT");
以下代码打印为我。
String json = "{\n" +
" \"RESULTS\": {\n" +
" \"ATTACHMENTS\": {\n" +
" \"ATTACHMENT\": [{\"key\": 1}, {\"key\": 2}]\n" +
" }\n" +
" }\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
node.get("RESULTS").get("ATTACHMENTS").get("ATTACHMENT").forEach(obj -> {
System.out.println(obj.get("key"));
});