如何将List <string>转换为JsonNode。我想从List中删除元素

时间:2018-05-17 21:49:11

标签: java json jackson

我想创建一个"tags":"Engineering"

的JSON节点
  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)

1 个答案:

答案 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"));