如何反序列化一个Map< String,Object>与GSON [英] How to de-serialize a Map<String, Object> with GSON
问题描述
$ b
code $ {
Thomas:{
age:32,
surname:Scott
},
Andy: {
age:25,
surname:Miller
}
}
我希望GSON使它成为一个Map,PersonData显然是一个Object。名称字符串是PersonData的标识符。
正如我所说我对GSON非常新颖,只尝试过类似的东西:
Gson gson = new Gson();
地图< String,PersonData> (jsonString,new TypeToken< Map< String,PersonData>>(){}。getType());
但是这个错误:
<$ p
$ 在线程main中的异常com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期的BEGIN_ARRAY,但在第1行的STRING 3141
任何帮助都会被赞赏:
以下作品为我 static class PersonData {
int age;
字符串姓氏;
public String toString(){
return[age =+ age +,surname =+ surname +];
public static void main(String [] args){
String json ={\Thomas \:{\年龄......:32,姓氏:斯科特,安迪,年龄,25岁,姓氏 :\Miller \}};
System.out.println(json);
Gson gson = new Gson();
地图< String,PersonData>解码= gson.fromJson(json,新的TypeToken< Map< String,PersonData>>(){}。getType());
System.out.println(已解码);
打印
{Thomas:{age:32,surname:Scott},Andy:{age:25,surname:Miller} }
{Thomas = [age = 32,姓氏= Scott],Andy = [年龄= 25,姓氏= Miller]}
因此,也许你的 PersonData
类是非常不同的。
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 :)
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.
这篇关于如何反序列化一个Map< String,Object>与GSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!