简体   繁体   中英

map json object with dynamic key to java object

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;

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM