1

I receive JSON data from web service and I would like to convert it into Java object. The ways are many, however I don't find any that could deal with changeble array keys that I receive in the json.

JSON example:

{
    "total": 2,
    "last": "AAAI9Zgh",
    "results": {
        "67701510/2/1150671": {
            "attributes": {
              "200": "11444413213123",
              "201": "Frank"     
            },
            "id": "67701510/2/1150671"
        },
       "76701410/3/1330671": {
            "attributes": {
              "200": "11666613213123",
              "201": "Mary"
            },
            "id": "76701410/3/1330671"
        }
    }
}

In the results there are 2 objects. Name of each object is an ID of the object so it is changeble. The method like this

return new Gson().fromJson(json, clazz);

is not working.

I would like to reach attributes and id data in each object.

Could anyone give some method to do so?

2
  • 1
    Use a Map<String, yourObject> for the mapping. Commented May 4, 2017 at 14:00
  • 1
    Great! That works! Please open an answer so that I could "+" it. Commented May 4, 2017 at 14:08

2 Answers 2

1

Well if you have dynamic keys in your JSON, they can be mapped as Map<String, Object>.

Let's say you have a class Result that wraps the Results attributes, you just need to use Map<String, Result> in your GSON mapping.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use jackson a java library and convert the JSON string to java Map.

ObjectMapper mapper = new ObjectMapper()
Map parsedJson = mapper.readValue(json,Map.class)

Then the parsedJson variable will be a Map containing the parsed json.

Sorry for not showing example in GSON, I am less familiar with this library.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.