2

how do i map the below json to a java class, where the key is dynamic

{
    "steps":
    {
        "1":{
                a:"a",
                b:"b",
                c:"c"
            },
        "2":{ 
                a:"a",
                b:"b",
                c:"c"
            },
        "3":{ 
                a:"a",
                b:"b",
                c:"c"
            }
    }
}

Normally, if the json object is of this kind, it is easy to map to an object.

{
    "steps":
    [
        {
            a:"a",
            b:"b",
            c:"c"
        },
        {
            a:"a",
            b:"b",
            c:"c"
        },
        {
            a:"a",
            b:"b",
            c:"c"
        }
    ]
}

And the class for this will be:

public class Example
{
    private Steps[] steps;

}

public class Steps
{
    private String b;

    private String c;

    private String a;

}
3
  • Have you tried this?: stackoverflow.com/questions/17824674/… Commented Jul 28, 2015 at 18:17
  • Use map for steps instead of array. Commented Jul 28, 2015 at 18:25
  • Thanks using Map works Commented Jul 29, 2015 at 9:18

1 Answer 1

7

Just in case someone else come looking for same/similar problem. A Map should be used in case the keys are dynamic. In this case, Example class would look something like:

public class Example
{
    private Map<String, Steps> steps;

}

In HashMap, keys insertion order is not preserved, therefore LinkedHashMap should be used if insertion order of keys matter.

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

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.