Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

java - How to de-serialize a Map<String, Object> with GSON

i am fairly new to GSON and get a JSON response of this format (just an easier example, so the values make no sense):

{
    "Thomas": {
        "age": 32,
        "surname": "Scott"
    },
    "Andy": {
        "age": 25,
        "surname": "Miller"
    }
}

I want GSON to make it a Map, PersonData is obviously an Object. The name string is the identifier for the PersonData.

As I said I am very new to GSON and only tried something like:

Gson gson = new Gson();
Map<String, PersonData> decoded = gson.fromJson(jsonString, new TypeToken<Map<String, PersonData>>(){}.getType());

but this threw the error:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 3141

Any help is appreciated :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following works for me

static class PersonData {
    int age;
    String surname;
    public String toString() {
        return "[age = " + age + ", surname = " + surname + "]";
    }
}

public static void main(String[] args) {
    String json = "{"Thomas": {"age": 32,"surname": "Scott"},"Andy": {"age": 25,"surname": "Miller"}}";
    System.out.println(json);
    Gson gson = new Gson();
    Map<String, PersonData> decoded = gson.fromJson(json, new TypeToken<Map<String, PersonData>>(){}.getType());
    System.out.println(decoded);
}

and prints

{"Thomas": {"age": 32,"surname": "Scott"},"Andy": {"age": 25,"surname": "Miller"}}
{Thomas=[age = 32, surname = Scott], Andy=[age = 25, surname = Miller]}

So maybe your PersonData class is very different.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...