Parse implicit JSON list given by keys "1", "2"

I’m receiving this JSON from an API.

{
    "message" : "message",
    "1": {
        "packageCode": "packageCode1",
        "packageNum": "packageNum1"
    },
    "2": {
        "packageCode": "packageCode2",
        "packageNum": "packageNum2"
    }
}

Is it possible to convert it to a java object with the below attributes?

  • String message
  • Package [] packages

I’m using jackson-databind ObjectMapper.

Thank you!

>Solution :

It is better to change the API, which returns this JSON to return an array of packages.

{
    "message" : "message",
    "packages": [
    {
        "packageCode": "packageCode1",
        "packageNum": "packageNum1"
    },
    {
        "packageCode": "packageCode2",
        "packageNum": "packageNum2"
    }]
}

If this cannot be changed, you’ll need to write a custom deserealizer by extending the StdDeserializer<T> class. You’ll have to programmatically inspect the JsonNode parse tree and assemble the object that you want.

This article explains how to do it and comes with a working code sample.

Leave a Reply