改造 - 解析JSON

时间:2016-08-12 06:23:04

标签: android json gson retrofit

我遇到一种JSON问题。

示例:

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

我总是用Gson将json转换为POJO。我使用的是Retrofit 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;
}

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

如果您的JSON具有可变密钥,则必须手动反序列化,因此我认为最佳解决方案是将您的JSON响应更改为:

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

public class Response {
    public Example[] examples;
}

答案 1 :(得分: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;
}

答案 2 :(得分:0)

我找到了解决方案:

我使用private String getDateTime() { // get date time in custom format SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); return sdf.format(new Date()); } 作为回复

后来:

Gson.JsonObject
相关问题