【问题标题】:How to read nested JSON arrays with Retrofit and Jackson?如何使用 Retrofit 和 Jackson 读取嵌套的 JSON 数组?
【发布时间】:2015-07-08 21:28:40
【问题描述】:

在我的 Android 应用程序中,我使用 Retrofit 来描述内部 API:

@Provides
@Singleton
ProductsService provideProductsService() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setPropertyNamingStrategy(
        PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    RestAdapter.Builder restAdapterBuilder = new RestAdapter.Builder()
        .setConverter(new JacksonConverter(objectMapper));
    return restAdapterBuilder
        .setEndpoint(Endpoints.newFixedEndpoint("http://192.168.1.1"))
        .build()
        .create(ProductsService.class);

为了阅读ProductLevels,我创建了以下界面:

public interface ProductsService {

    @GET("/api/products/{productId}/levels/")
    public Observable<List<ReadProductLevelsResponse>> readProductLevels(
            @Path("productId") int productId
    );

}

这是由后端提供的 JSON 字符串:

[
    [
        1427378400000,
        553
    ],
    [
        1427382000000,
        553
    ]
]

当我尝试读取空 ReadProductLevelsResponse 类中的 JSON 数据时,会出现以下错误:

com.fasterxml.jackson.databind.JsonMappingException:无法从 [来源:retrofit.ExceptionCatchingTypedInput$ExceptionCatchingInputStream@11ae0f16; 的 START_ARRAY 令牌中反序列化 ReadProductLevelsResponse 的实例;行:1,列:2](通过引用链:java.util.ArrayList[0])

如何将 JSON 数据读入 ReadProductLevelsResponse 类?

【问题讨论】:

  • 你试过@GET("/api/products/{productId}/levels/") public Observable>> readProductLevels(@Path("productId") int productId );

标签: android arrays json jackson retrofit


【解决方案1】:

我发现by this answer 我必须使用List&lt;List&lt;Double&gt;&gt; 作为响应类型。

public interface ProductsService {

    @GET("/api/products/{productId}/levels/")
    public Observable<List<List<Double>>> readProductLevels(
            @Path("productId") int productId
    );

}

跟进问题:How to transform a nested list of double values into a Java class using RxJava?

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 2019-09-25
    相关资源
    最近更新 更多