我是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
任何帮助表示赞赏:)
解决方法:
以下适用于我
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类非常不同.