复杂的Json对象到Java对象,带有Gson的Map字段

时间:2015-08-27 23:03:15

标签: java json gson

我有一个像这样的Json结构:

{
   "Pojo" : {
       "properties" : {
          "key0" : "value0",
          "key1" : "value1"
       }
   }
}

我希望我的最终结果看起来像这样:

public class Pojo {
     public Map<String, String> properties;
}

但我得到的是这样的东西:

public class Pojo {
   public Properties properties;
}

public class Properties {
  public String key0;
  public String key1;
}

现在,我正在为解析Json而做的就是:

new Gson().fromJson(result, Pojo.class)

关于我需要做些什么才能正确设置?我没有能力改变Json返回对象的结构。

2 个答案:

答案 0 :(得分:2)

Gson正在尝试将JSON字段名称与POJO字段进行匹配,因此您在JSON之上意味着顶级对象具有名为“Pojo”的字段。实际上,它表明了以下类结构,

class Container {
    MyObject Pojo;
}

class MyObject {
    Map<String, String> properties;
}

其中类MyObjectContainer的名称完全是任意的。 Gson匹配字段名称,而不是对象类型名称。

您可以使用简单的语句反序列化该对象 -

Container container = gson.fromJson(result, Container.class);

您的地图为container.Pojo.properties

如果你不想拥有额外的容器类,你可以先解析一个Json树,然后再添加你感兴趣的部分 -

JsonElement json = new JsonParser().parse(result);
// Note "Pojo" below is the name of the field in the JSON, the name 
// of the class is not important
JsonElement pojoElement = json.getAsJsonObject().get("Pojo");
Pojo pojo = gson.fromJson(pojoElement, Pojo.class);

然后你的地图在pojo.properties,这就是我想你想要的。为了清楚起见,我没有进行错误检查,但你可能想添加一些。

答案 1 :(得分:0)

试试这个:

JSONObject obj1=new JSONObject(jsonString);
JSONObject obj2=obj1.getJSONObject("Pojo");
JSONObject obj3=obj2.getJSONObject("properties");
String key1=obj3.getString("key0");
String key2=obj3.getString("key1");

有关更多参考,请尝试链接:

https://androidbeasts.wordpress.com/2015/08/04/json-parsing-tutorial/

相关问题