GSON:无法正确解析JSON对象
问题描述:
我试图解析像GSON以下JSON对象:GSON:无法正确解析JSON对象
{
"key1":"someValue",
"key2":{
"anotherKey1":"212586425",
"anotherKey2":"Martin"
}
}
这是代码:
Data data = new Gson().fromJson(json, Data.class);
这里是Data
类:
public class Data {
public String key1;
public Map key2; //This will break everything.
}
我期望的是(我是GSON的新手),它产生的值为key2
作为Map
对象。
但是,我得到一个错误Expected BEGIN_OBJECT but was STRING
,这让我觉得我传递一个String
,我应该传递一个JSON对象。
是不是GSON解析了我在开始时传递的整个JSON字符串?所以最终,我希望新的数据源是一个Map
对象。这是可行的吗?
答
让Gson做这项工作。我定义Data
作为
package *.questions.q19228349;
public class Data {
@Override
public String toString() {
return "Data [key1=" + key1 + ", key2=" + key2 + "]";
}
public String key1;
public Object key2;
}
,然后我可以为key2
解析这两种情况下:
package *.questions.q19228349;
import com.google.gson.Gson;
public class Q19228349 {
public static void main(String[] args){
String json =
"{\"key1\":\"someValue\","+
"\"key2\":{ "+
" \"anotherKey1\":\"212586425\","+
" \"anotherKey2\":\"Martin\""+
" }"+
" }";
String json2 =
"{\"key1\":\"someValue\","+
"\"key2\":\"aString\""+
" }";
Gson g = new Gson();
Data d = g.fromJson(json, Data.class);
System.out.println("First: " +d);
Data d2 = g.fromJson(json2, Data.class);
System.out.println("Second: "+d2);
}
}
这是结果:
第一:数据[KEY1 = someValue中,键2 = { anotherKey1 = 212586425, anotherKey2 = Martin}] Second:Data [key1 = someValue,key2 = aString]
这对我来说非常好。你确定你使用的是正确的JSON吗? –
@SotiriosDelimanolis奇怪。我的JSON对象中的结构完全相同。不能让它工作,虽然... –
你能打印出你正试图解析的JSON吗? –