如何使用GSON </string,>反序列化Map <string,object =“”>

时间:2013-12-11 15:50:45

标签: java serialization gson

我是GSON的新手,并获得了这种格式的JSON响应(只是一个更简单的例子,因此值没有意义):

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

我希望GSON将其设为Map,PersonData显然是一个Object。名称字符串是PersonData的标识符。

正如我所说,我对GSON很陌生,只尝试过类似的事情:

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

但这引发了错误:

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

感谢任何帮助:)

2 个答案:

答案 0 :(得分:25)

以下为我工作

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);
}

并打印

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

所以也许你的PersonData课程非常不同。

答案 1 :(得分:2)

您可以使用gson.toJsonTree(Object o)将自定义对象转换为JSON格式。

以下适用于我:

private static class PersonData {
    private int age;
    private String surname;

    public PersonData(int age, String surname) {
        this.age = age;
        this.surname = surname;
    }
}

public static void main(String[] args) {
    PersonData first = new PersonData(24, "Yovkov");
    PersonData second = new PersonData(25, "Vitanov");

    Gson gson = new Gson();

    JsonObject jsonObject = new JsonObject();
    jsonObject.add("kocko", gson.toJsonTree(first));
    jsonObject.add("deyan", gson.toJsonTree(second));

    System.out.println(gson.toJson(jsonObject));

}

并打印:

{"kocko":{"age":24,"surname":"Yovkov"},"deyan":{"age":25,"surname":"Vitanov"}}