使用Jackson将Json数组拆分为单个的Json元素

4
有没有办法使用Jackson库将给定的Json数组拆分为单独的Json元素?例如,我有这个Json数组:
[
    {
        "key1":"value11", 
        "key2":"value12"
    },
    {
        "key1":"value21", 
        "key2":"value22"
    }
]

分割后,我希望得到一个单独元素的列表,例如:
{
        "key1":"value11", 
        "key2":"value12"
}

并且

{
        "key1":"value21", 
        "key2":"value22"
}
5个回答

11

解决这个问题的好方法是使用Java 8的流API进行迭代。 JsonNode对象是可迭代的,其中spliterator方法是可用的。 因此,可以使用以下代码:

public List<String> split(final String jsonArray) throws IOException {
    final JsonNode jsonNode = new ObjectMapper().readTree(jsonArray);
    return StreamSupport.stream(jsonNode.spliterator(), false) // Stream
            .map(JsonNode::toString) // map to a string
            .collect(Collectors.toList()); and collect as a List
}

另一种选择是跳过重新映射(调用 toString),而是返回一个List<JsonNode>元素。这样,您可以使用JsonNode方法访问数据(getpath等)。


1
最终,我找到了一个可行的解决方案:

public List<String> split(String jsonArray) throws Exception {
        List<String> splittedJsonElements = new ArrayList<String>();
        ObjectMapper jsonMapper = new ObjectMapper();
        JsonNode jsonNode = jsonMapper.readTree(jsonArray);

        if (jsonNode.isArray()) {
            ArrayNode arrayNode = (ArrayNode) jsonNode;
            for (int i = 0; i < arrayNode.size(); i++) {
                JsonNode individualElement = arrayNode.get(i);
                splittedJsonElements.add(individualElement.toString());
            }
        }
        return splittedJsonElements;
}

1

这是一行代码:

new ObjectMapper().readTree(json).forEach(node -> System.out.println(node.toString()));

0

你可能想要查看这个API


0

这似乎是作者所要求的。我使用Jackson库的toString方法将JSON列表拆分为两个字符串。

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

...
...
  
String jsonText = "[{\"test\":1},{\"test2\":2}]";
int currentElement = 0;
int elementCount;

ObjectMapper mapper = new ObjectMapper();

JsonNode jsonObj = mapper.readTree(jsonText);
 
elementCount = jsonObj.size();

while (currentElement<elementCount) {
    System.out.println(jsonObj.get(currentElement).toString());
    currentElement++;
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接