如何使用GSON反序列化Map<String,Object>

2022-09-03 10:08:05

我对GSON相当陌生,并获得了这种格式的JSON响应(只是一个更简单的例子,所以这些值没有意义):

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

我希望GSON使它成为一个Map,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

任何帮助是值得赞赏的:)


答案 1

以下内容对我有用

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


答案 2

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

以下内容对我有用:

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"}}