Retrofit - 解析JSON

4

I have a problem with one type of JSON.

Example:

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

感谢您的帮助。

我认为你需要这个: https://dev59.com/tlsX5IYBdhLWcg3wf_c8 - Ramit
3个回答

1
如果你的JSON具有可变键,则必须手动反序列化它,因此我认为最好的解决方案是将你的JSON响应更改为:
    [
      {"id" : 1, "value" : "name"}, 
      {"id" : 2, "value" : "example"}
    ]

and

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;
}

0
我找到了解决方案:
我使用 Gson.JsonObject 作为响应
然后:
  Type type = new TypeToken<Map<String, String>>(){}.getType();
  Map<String, String> myMap = new Gson().fromJson(jsonObject.toString(), type);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接