我想创建一个"tags":"Engineering"
带
JSON Example
{"tags": ["Engineering","Pharmacy","Chemical"],
"summary":"Science Streams",
"produces": ["application\/json","application\/xml"]
}
ObjectMapper mapper = new ObjectMapper();
List<Tags> tag = new ArrayList<Tags>();
ArrayNode array = mapper.valueToTree(tags);
ObjectNode objNode = mapper.valueToTree(array);
JsonNode result = mapper.createObjectNode().set("tags", objNode );
当我使用它时,我收到以下错误:
com.fasterxml.jackson.databind.node.ArrayNode incompatible with com.fasterxml.jackson.databind.node.ObjectNode
如果我使用
,我会得到NullPointerException
for(String tag:tagList)
答案 0 :(得分:0)
ArrayNode
有一个remove方法,用于删除数组索引。这是一个解析JSON字符串的简单示例,从该JSON中的数组中删除元素并将其打印出来。
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree("{\"tags\": [\"Engineering\",\"Pharmacy\",\"Chemical\"]}");
ArrayNode tags = (ArrayNode) tree.get("tags");
tags.remove(1);
mapper.writeTree(mapper.getFactory().createGenerator(System.out), tree);
如果您想用单个字符串值替换数组,您可以这样做:
((ObjectNode) tree).set("tags", new TextNode("Engineering"));