2016-08-12 49 views
3

我遇到了一种类型的JSON问题。翻新 - 解析JSON

例子:

{ 
    "1": "name", 
    "2": "example", 
    "3": "loremipsum", 
    "4": "etc", 
} 

我总是将JSON与GSON到的POJO。我使用的是改造1.9

但在这种情况下,其愚蠢的,因为我收到的对象,如:

public class Example { 

    @SerializedName("1") 
    @Expose 
    private String _1; 
    @SerializedName("2") 
    @Expose 
    private String _2; 
    @SerializedName("3") 
    @Expose 
    private String _3; 
    @SerializedName("4") 
    @Expose 
    private String _4; 
    ......... 

如何可以解析此JSON,包括接收对象的列表:

public class Example { 
    private int id; 
    private String value; 
} 

谢谢求助。

+0

我想你需要这个: - Ramit

回答

0

我找到了解决办法:

我以前Gson.JsonObject作为响应

及更高版本:

Type type = new TypeToken<Map<String, String>>(){}.getType(); 
    Map<String, String> myMap = new Gson().fromJson(jsonObject.toString(), type); 
1

如果你的JSON有可变的钥匙,你必须手动反序列化,所以我认为最好的办法是改变你的JSON回应:

[ 
     {"id" : 1, "value" : "name"}, 
     {"id" : 2, "value" : "example"} 
    ] 

public class Response { 
    public Example[] examples; 
} 
0

因为你的变量键,很难用GSON解析。

但是你可以使用JSONObject来做到这一点,它非常简单。有代码,我已经测试它,它的伟大工程:

private ArrayList<Example> parseJson() throws JSONException { 
    String json = "{\n" + 
      " \"1\": \"name\",\n" + 
      " \"2\": \"example\",\n" + 
      " \"3\": \"loremipsum\",\n" + 
      " \"4\": \"etc\"\n" + 
      "}"; 

    ArrayList<Example> exampleList = new ArrayList<>(); 
    JSONObject jsonObject = new JSONObject(json); 
    Iterator<String> iterator = jsonObject.keys(); 
    while(iterator.hasNext()) { 
     Example example = new Example(); 
     String id = iterator.next(); 
     example.id = Integer.parseInt(id); 
     example.value = jsonObject.getString(id); 

     exampleList.add(example); 
    } 
    return exampleList; 
}