android - 如何使用改造将 JSON 作为字符串

标签 android json rest api retrofit2

拜托,我是改造的新手,我已经被困了几个星期了,我尝试将我的响应作为 POJO 类并最终得到这个错误“Json 文档未完全消耗”,我已经搜索并询问这个问题在这里,没有人能够帮助摆脱这个问题

现在我想从改造中获取我的 JSON 作为字符串,这样我就可以自己手动转换为我的 POJO 类并且不知道如何获取响应 JSON 作为字符串

我需要你的帮助,我已经坚持了 3 周

最佳答案

只需将响应类型设置为字符串

@GET("api/offers")
Call<String> loadOffers(); 

代替

@GET("api/offers")
Call<List<Offer>> loadOffers(); 

将此添加到您的 build.gradle 文件中

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

并且在 public static Retrofit getRetrofitInstance() {

在函数末尾添加这些行。重要的部分是转换工厂

if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

然后您可以将数据作为 JSON 字符串获取

MyApi service = RetrofitClientInstance.getRetrofitInstance().create(MyApi.class);


        Call<String> callTypes = service.loadOffers();

        callTypes.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response {                    
                String urJson  = response.body() ; 
               //  DO UR STUFF HERE
            }

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

            }
        });

希望对您有所帮助。

关于android - 如何使用改造将 JSON 作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53633849/

相关文章:

android - 在android中以pdf格式显示sqlite数据库内容

json - Grails-在 Controller 中生成自定义JSON时出错

php - 存储和检索数百万个 JSON 编码的事件(PHP/数据库)

java - 在API响应中返回Enum的值而不是Spring boot中的名称

rest - 在 REST 查询中指定数据结构

python - django-rest-framework:为什么我的 API 为我的 ENUMS 返回键而不是值?

Android视频去除色度键背景

Android:我可以在我的应用程序中使用 adb 命令吗?

java - android 代码在使用 switch 语句时似乎出现错误

python - 如何通过 python API 将 json/pickle 文件转储和读取到 Google Drive?