2015-08-27 73 views
0

地圖領域的Java對象我有一個JSON結構,像這樣:複雜JSON對象,以與GSON

{ 
    "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

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,這是我認爲ÿ你想要。爲了清晰起見,我沒有進行錯誤檢查,但您可能需要添加一些。

+0

感謝您幫助我理解Gson在這裏嘗試做什麼。這是我第一次嘗試解析器。 – swhite