Destroy JSON wrapped in an object with an unknown property name using Jackson

I am using Jackson to deserialize JSON from the ReST API for Java using Jackson.

The problem I ran into is that one specific ReST answer goes back to the object referenced by the numeric identifier, for example:

{
  "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 (possibly naive) approach to JSON deserialization until this point was to create a POJO of the mirror image and let Jackson easily and automatically display all the fields, which is good.

, ReST JSON , POJO, . POJO, , Java.

, .

+4
2

- @JsonAnySetter. .

:

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

, :

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

, @JsonAnyGetter, Map<String, List<Stuff>) .

+3

, JsonDeserializer. , .

, :

+1

All Articles