Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

json - Jackson parser handling of multiplefield names with same name

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...