Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson start deserialization two levels down

Tags:

java

jackson

I have an awkwardly constructed json file like this:

{
"clientByClientId" : {
  "123" : {
    "clientId" : "123"
     "moreFields" : "moreData"
   }
  "456" : {
    "clientId" : "456"
     "moreFields" : "moreData"
   }
 }
}

As you can see, the top two levels of this json are superfluous. What is the best way to deserialize this into a collection of Client objects? I tried using online json to pojo tools, but they ended up generating classes called "123" and "456". Ideally, I'd like to use Jackson, but am open to other solutions.

like image 313
Steve Avatar asked Aug 14 '26 13:08

Steve


1 Answers

Small note: your JSON is malformed, as it is missing a few commas. Once those are added, then this will work for you.

First off, you'll need a class to represent a Client:

public class Client {
    private final int clientId;
    private final String moreFields;

    @JsonCreator
    public Client(@JsonProperty("clientId") int clientId, 
                  @JsonProperty("moreFields") String moreFields) {
        this.clientId = clientId;
        this.moreFields = moreFields;
    }

    @Override
    public String toString() {
        return "Client[clientId=" + clientId + ", moreFields=" + moreFields + "]";
    }
}

Now, you just need to create your ObjectMapper and iterate over the elements of your clientByClientId map, which can be done with the following:

ObjectMapper objectMapper = new ObjectMapper();
JsonNode node = objectMapper.readTree(json).get("clientByClientId");
Map<Integer, Client> clientMap = objectMapper.readValue(node.traverse(),
        new TypeReference<Map<Integer, Client>>() {});
System.out.println(clientMap.values());

The output of this code is:

[Client[clientId=123, moreFields=moreData], Client[clientId=456, moreFields=moreData]]
like image 137
Jacob G. Avatar answered Aug 16 '26 14:08

Jacob G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!