Jackson 解析器处理同名的多字段名称 [英] Jackson parser handling of multiplefield names with same name

查看:41
本文介绍了Jackson 解析器处理同名的多字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为 Jackson JSON 解析器的一个特性是我的案例的固有问题.我要解析一个可能不符合 json 格式的未知文件,从而最终有多个相同的键名.在这种情况下,如果我在其上调用 getFieldNames() 之类的函数,它最终只会在这些多个相同的简单元素中提供一个条目.因此,如果我对它执行 get(String) 操作,我最终只会得到那些具有相同键值的 Json 节点之一,而我应该得到所有其他节点对此有何评论或解决方案?

I see a feature of Jackson JSON parser as an inherent problem for my case. I am to parse an unknown file which might not comply with the json formats, thereby end up having multiple key names that are same. In that case, if i call a function like getFieldNames() on it , it ends up giving only one entry among those multiple same simple elements. So if i do a get(String) on it, i'll end up getting only one of those Json nodes having the same key value where as i'm supposed to get all the others Any comments or solutions on this?

推荐答案

大多数 JSON 解析器会立即拒绝您的输入文件,因为不允许在同一嵌套级别出现重复的键(这是事实上的标准).但是,某些解析器将允许您以多种方式处理重复项.

Most JSON parsers will reject your input file out of hand, as duplicate keys at the same nesting level are not allowed (this is a de-facto standard). However, certain parsers will allow you to handle the duplicate in a variety of ways.

在 Jackson 中处理此问题的一种方法是将常规属性映射到实体类,然后通过 @JsonAnySetter.

One way to handle this in Jackson, would be to map regular attributes into an entity class, then handle the potential duplicates via a @JsonAnySetter.

public class Bag {
    final transient Multimap<String, Object> multimap = LinkedListMultimap
            .create();

    // regular properties, constructors etc

    @JsonAnySetter
    public void add(final String key, final String value) {
        multimap.put(key, value);
    }
}

注意多重映射的使用:常规哈希映射不能包含重复的键,因此多重映射是工作解决方案的必要条件.反序列化输入文件后,所有常规"JSON 属性都将映射到其对应的实体属性,而所有重复项将存储在映射中,可供手动处理.

Note the use of a multimap: regular hash maps cannot contain duplicate keys, so a multimap is a requirement for a working solution. After deserializing the input file, all 'regular' JSON attributes will be mapped to their corresponding entity properties, whereas all duplicates will be stored in the map, and available for manual processing.

final List<Object> duplicatedValues = multimap.get(someKey);

或者,您可以创建一个自定义反序列化器,它接收所有令牌(无论它们是否重复).

Alternatively, you could create a custom deserializer, which will recieve all tokens (regardless of wether they are duplicates or not).

这篇关于Jackson 解析器处理同名的多字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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