简体   繁体   中英

GSON How to deserialize to a class with this array json string

I am struggling to find a way to serialize / deserialize this JSON output to a Java class? Can anyone provide code sample?

[
    {
        "topic": "this is my topic"
    },
    [
        {
            "name": "John"
        },
        {
            "age": 100
        }
    ]
]

My current attempt uses this Javabean:

public class Test {
    private String topic;
    private List<Person> listOfPersons;
}

Which I try to deserialize data into using Gson:

gson.fromJson(this.json, Test[].class);

But the deserialization fails, because Gson is looking for a list of persons in the JSON, but it doesn't exist.

It doesn't seem like having an object next to an array, inside an array, is sensical. It would make sense to put things this way:

{
    "topic": "this is my topic",
    "listOfPersons" : [
        {
            "name": "John",
            "age": 100
        },
        {
            ... another person
        }
    ]
}

Then you could just have a Person class:

public class Person {
    private String name;
    private int age;
}

...and you could deserialize with the code you already have.

The problem here is that your JSON data is syntactically correct, but semantically ambiguous. And by that I mean, it appears to represent a polymorphic array, where each item in the array is of a different type.

In addition, the portion representing a 'person' seems to have been de-normalized horribly, where each attribute of a person is represented as a separate object in an array. Quite weird indeed. Unfortunately its really impossible to tell what types are represented just by looking at the data alone, and there are no hints provided to allow Gson to deserialize the data for you. The best you can do in this case is manually parse the information.

Test test = new Test();
JsonArray rootArray = new JsonParser().parse(jsonString);
test.setTopic(rootArray.get(0).get("topic");

Person person = new Person();
JsonArray personArray = rootArray.get(1);
person.setName(personArray.get(0).get("name"));
person.setAge(personArray.get(1).get("age"));

test.setListOfPersons(Arrays.asList(person));

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