【问题标题】:Retrofit - parse JSON改造 - 解析 JSON
【发布时间】:2016-12-19 01:40:35
【问题描述】:

我对一种 JSON 类型有疑问。

例子:

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

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

感谢您的帮助。

【问题讨论】:

  • 我认为你需要这个:- stackoverflow.com/questions/33758601/…>

标签: android json gson retrofit


【解决方案1】:

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

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

public class Response {
    public Example[] examples;
}

【讨论】:

    【解决方案2】:

    由于您的变量键,很难用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;
    }
    

    【讨论】:

      【解决方案3】:

      我找到了解决办法:

      我使用Gson.JsonObject 作为回复

      后来:

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

      【讨论】:

        猜你喜欢
        • 2016-04-27
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2020-04-10
        • 1970-01-01
        • 2019-01-28
        • 1970-01-01
        相关资源
        最近更新 更多