解析包含重复键的json [英] Parsing a json which contains duplicate keys

查看:717
本文介绍了解析包含重复键的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Jackson 库解析具有重复键的无效结构的json。如果json有重复键,我想将它们解压缩为 Collection

I'm trying to parse json with invalid structure which has duplicate keys using Jackson library. If a json has duplicate keys, I would like to extract them as a Collection.

我正在尝试解析的示例(我正在尝试解析的实际json来自 Wireshark json export):

Example of what I'm trying to parse (the actual json that I'm trying to parse comes from Wireshark json export):

{
    "a": "a",
    "a": {
        "b": {

        },
        "b": true
    }
}

但是,由于此json具有重复键,因此仅保留最后一个值:

However, since this json has duplicate keys, only the last value is retained:

JsonNode tree = new ObjectMapper().readTree(json);
System.out.println(tree); // {"a":{"b":true}}

我也试过了 Guava 模块,它具有 Multimap 支持,但是对于嵌套的json对象,它不能正常工作。

I've also tried the Guava module which has Multimap support, however it doesn't work as expected for nested json objects.

使用我之前显示的json的Guava模块示例:

Example using Guava module for the json that I have shown before:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new GuavaModule());
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

Multimap read = mapper.readValue(json, Multimap.class);
System.out.println(read); // {a=[a, {b=true}]}

我该如何解决这个问题使用 Jackson 库?是否还有其他库可以支持解析java的json结构?

How should I tackle this problem using Jackson library? Are there any other libraries which would support parsing of such json structure for java?

推荐答案

如果你对json库很灵活,你可以使用 net.sf.json.JSONObject

If you are flexible with json library you can make use of net.sf.json.JSONObject.

这个库将保留重复的值,将它们存储到阵列。如果有多个相同的键可用,它将创建一个键,将所有值作为数组。

This library will retain the duplicated values by storing them into arrays. If multiple same keys are available it will create one key will all the values as Array.

此外,编码部分只是一行。一旦使用net.sf.json.JSONObject解析了json,就可以将它提供给jackson库。

And also the coding part is just a single line. Once you parsed the json using net.sf.json.JSONObject then you can supply this to jackson library.

JSONObject jsonObject = JSONObject.fromObject( "{ \"a\": \"a\", \"a\": { \"b\": {},\"b\": true}}" );

System.out.println( "net.sf.json.JSONObject: " + jsonObject );

JsonNode jsonNode = new ObjectMapper().readTree( jsonObject.toString() );

System.out.println( "com.fasterxml.jackson.databind.JsonNode" + jsonNode );

输出:

net.sf.json.JSONObject: {"a":["a",{"b":[{},true]}]}
com.fasterxml.jackson.databind.JsonNode{"a":["a",{"b":[{},true]}]}

的maven依赖关系net.sf.json

Maven dependency of net.sf.json

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

这篇关于解析包含重复键的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆