Search code examples
javajsonjacksonjson-deserialization

Deserialize a JSON wrapped in an object with an unknown property name using Jackson


I'm using Jackson to deserialize JSON from a ReST API to Java objects using Jackson.

The issue I've run into is that one particular ReST response comes back wrapped in an object referenced by a numeric identifier, like this:

{
  "1443": [
    /* these are the objects I actually care about */
    {
      "name": "V1",
      "count": 1999,
      "distinctCount": 1999
      /* other properties */
    },
    {
      "name": "V2",
      "count": 1999,
      "distinctCount": 42
      /* other properties */
    },
    ...
  ]
}

My (perhaps naive) approach to deserializing JSON up until this point has been to create mirror-image POJOs and letting Jackson map all of the fields simply and automatically, which it does nicely.

The problem is that the ReST response JSON has a dynamic, numeric reference to the array of POJOs that I actually need. I can't create a mirror-image wrapper POJO because the property name itself is both dynamic and an illegal Java property name.

I'd appreciate any and all suggestions for routes I can investigate.


Solution

  • The easiest solution without custom deserializers is to use @JsonAnySetter. Jackson will call the method with this annotation for every unmapped property.

    For example:

    public class Wrapper {
      public List<Stuff> stuff;
    
      // this will get called for every key in the root object
      @JsonAnySetter
      public void set(String code, List<Stuff> stuff) {
        // code is "1443", stuff is the list with stuff
        this.stuff = stuff;
      }
    }
    
    // simple stuff class with everything public for demonstration only
    public class Stuff {
      public String name;
      public int count;
      public int distinctCount;
    }
    

    To use it you can just do:

    new ObjectMapper().readValue(myJson, Wrapper.class);
    

    For the other way around you can use @JsonAnyGetter which should return a Map<String, List<Stuff>) in this case.