复杂 Json 对象到 Java 对象与 Map 字段与 Gson

Complex Json Object to Java object with Map field with 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 return 对象的结构。

试试这个:

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");

如需更多参考,请尝试 link:

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

Gson 正在尝试将 JSON 字段名称与 POJO 字段匹配,因此您在 JSON 上方暗示顶级对象有一个名为 'Pojo' 的字段。其实就是表示下面的class结构,

class Container {
    MyObject Pojo;
}

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

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

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

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

你的地图 container.Pojo.properties

如果你不想有额外的容器class,你可以先解析成一棵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,我想这就是你想要的。为清楚起见,我省略了错误检查,但您可能想要添加一些。