GSON:无法正确解析JSON对象

时间:2013-10-07 15:08:54

标签: java json parsing gson

我正在尝试使用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对象。这可行吗?

1 个答案:

答案 0 :(得分:0)

让Gson做好工作。我将Data定义为

package stackoverflow.questions.q19228349;

public class Data {

    @Override
    public String toString() {
        return "Data [key1=" + key1 + ", key2=" + key2 + "]";
    }
    public String key1;
    public Object key2;

}

然后我可以解析key2的两种情况:

package stackoverflow.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,key2 = {anotherKey1 = 212586425,   anotherKey2 = Martin}]第二名:数据[key1 = someValue,key2 = aString]