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

v8wbuo2f  于 2023-11-18  发布在  其他
关注(0)|答案(2)|浏览(146)

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

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

字符串
我想让GSON把它变成一个Map,PersonData显然是一个Object。name字符串是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


任何帮助是赞赏:)

huus2vyu

huus2vyu1#

下面的示例对我很有用

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类可能非常不同。

cld4siwp

cld4siwp2#

您可以使用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"}}

相关问题