Parse Jackson parser with multiple field names with same name

I see the Jackson JSON parser feature as an integral issue for my business. I have to parse an unknown file, which may not correspond to json formats, and in the end will have several key names that are the same. In this case, if I call a function like getFieldNames () on it, it ends up giving only one entry among those few simple elements. So if I get (String) on ​​it, I end up only getting one of these Json nodes with the same key value, where, how should I get all the rest Any comments or solutions on this?

+5
source share
1 answer

Most JSON parsers will reject your input file out of control, since duplicate keys at the same level are not allowed (this is the de facto standard). However, some parsers will allow you to handle the duplicate in various ways.

One way to deal with this in Jackson is to map regular attributes to an entity class, and then handle potential duplicates with @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);
    }
}

Pay attention to the use of multimap: regular hash cards cannot contain duplicate keys, so multi-frame processing is required for a working solution. After deserialization of the input file, all the “regular” JSON attributes will be mapped to the corresponding entity properties, while all duplicates will be saved on the map and available for manual processing.

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

, ( , ).

+4

All Articles