如何使用改型处理对象列表或单个对象的JSON响应? [英] How to handle JSON response of either a list of objects or a single object using retrofit?

查看:144
本文介绍了如何使用改型处理对象列表或单个对象的JSON响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用改造来调用REST服务(不是我的),该改造要么返回对象列表(如果有多个),要么返回一个对象列表(如果有).我可以在此处找到类似的问题,但是建议是更改我无法控制的API.我还阅读了

I am calling a REST service (not mine) using retrofit which either returns a list of objects (if there are multiple) or a single object (if one). I was able to find a similar issue here however the suggestion is to change the API which i don't have control of. I also read this thread which seems to be a good approach but is there a way to handle this using Retrofit?

推荐答案

虽然@pirho的答案似乎适用,但我发现了一个适用于我的不同且简单的解决方案.希望它也可以对其他人有所帮助.

While the answer from @pirho seems to be applicable, I found out a different and simple solution which worked for me. Hopefully it may help others as well.

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(JacksonConverterFactory.create(mapper))
            .client(okHttpClient)
            .build();

这篇关于如何使用改型处理对象列表或单个对象的JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆