【问题标题】:Converting JSON key - value pair into Java object using Retrofit when one of the key in json contains a list of values当 json 中的一个键包含值列表时,使用 Retrofit 将 JSON 键值对转换为 Java 对象
【发布时间】:2020-06-14 06:40:50
【问题描述】:

我正在学习通过 Retrofit 在 Android 中进行 API 调用,但由于使用 Retrofit 库将 JSON 转换为 java 对象而卡住了。我已经详细解释了这个问题,如下所示。如果有人能提供帮助,将不胜感激。

我有以下 JSON 作为我的 API 的响应 ---

[
  {
   "key1": "value1",
   "key2": "value2",
   "key3": "["v1", "v2", "v3"]"
  }
]

在 android 环境中,我使用改造来调用 API。 我做了以下POJO----

public class apiResponsePOJO implements Serializable {
    @SerializedName("key1")
    @Expose
    private String key1;

    @SerializedName("key2")
    @Expose
    private String key2;

    @SerializedName("key3")
    @Expose
    private List<String> key3;

    // I have created the getter and setter methods for all the three attributes.
}

APIInterface 类包含以下 GET 方法定义 --

    @GET("attribute/")
    Call<apiResponsePojo> getAttribute(@Query("attributeID") Integer attributeID);

我在 Fragment 类之一中调用 API 接口,如下所示 --

    APIInterface apiInterface = APIClient.getClient(url).create(APIInterface.class);
    getAttributeDetails(attributeID);

getAttributeDetails方法的定义如下——

public void getAttributeDetails(int attributeID) {
        Call<apiResponsePOJO> call = apiInterface.getAttribute(attributeID);
        call.enqueue(new Callback<apiResponsePOJO>() {
            @Override
            public void onResponse(Call<apiResponsePOJO> call, Response<apiResponsePOJO> response) {
                apiResponseDetails = response.body();

                Log.e("Server", "response = " + apiResponseDetails.getValue1());
            }

            @Override
            public void onFailure(Call<apiResponsePOJO> call, Throwable t) {

                Log.e("Server", t.getMessage());
//              t.printStackTrace();
            }
        });
    }

我收到的错误是:第 15 行第 20 列路径 $.key3 的未终止对象

谁能解释一下为什么会这样?

【问题讨论】:

    标签: java android json serialization retrofit2


    【解决方案1】:

    您的回复格式错误,key3 是 JSONArray,所以没有引号

    应该是:

    [ { "key1": "value1", "key2": "value2", "key3": ["v1", "v2", "v3"] } ]

    【讨论】:

    • 我在"["v1", "v2", "v3"]" 之前收到的输出来自 API。我需要将 API 响应从 "["v1", "v2", "v3"]" 更改为 ["v1", "v2", "v3"],这就是您在上面提到的,并且效果很好。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2021-10-19
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2022-08-17
    相关资源
    最近更新 更多