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

查看:71
本文介绍了解析包含重复键的 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 导出):

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}}

我也尝试过支持 MultimapGuava 模块,但是它对于嵌套的 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 库解决这个问题?是否有任何其他库支持解析此类 json 结构的 java?

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 with 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]}]}

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天全站免登陆