简体   繁体   English

如何在翻新中解析Restfull API JSON响应?

[英]How to parse Restfull api JSON response in retrofit?

I have a typical Retrofit API request. 我有一个典型的Retrofit API请求。 I have used a vb.net API call and it returns the response as bellow. 我使用了vb.net API调用,它返回的响应如下。

<string xmlns="http://tempuri.org/"> {"UserTickets":[{"Type":"Application","Category":"Mobile App","Sub Category":"Other","Issue Details":"Dummy","LMDT":"2019-11-14 15:46:00.000","ResponsibleEmail":"alex@goba.com"}],"success":"true","status:":"1"}</string>

I can't able to get a response body using the below code. 我无法使用以下代码获取响应正文。 How can I fetch a response-body from the response object? 如何从响应对象获取响应主体? May anyone help me?. 谁能帮我吗? API Call Android Code as bellow: API调用Android代码如下:

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

            Gson gson = new GsonBuilder()
                    .setLenient()
                    .create();

            mRetrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();

CryptocurrencyService scalarService = mRetrofit.create(CryptocurrencyService.class);
            Call<String> stringCall = scalarService.getStringResponse("800028");
            stringCall.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    if (response.isSuccessful()) {
                        String responseString = response.body().toString();
                        // todo: do something with the response string
                        Log.e("TAG_RESPONSE", responseString);
                    }
                }

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

                }
            });

The problem is that your response is not JSON, that's why you are not able to get the response. 问题是您的响应不是JSON,这就是为什么您无法获得响应。

Instead, if your response is a plain string you should add a Retrofit scalar converter com.squareup.retrofit2:converter-scalars:2.5.0 , you can see an example here . 相反,如果您的响应是纯字符串,则应添加Retrofit标量转换器com.squareup.retrofit2:converter-scalars:2.5.0 ,您可以在此处看到示例。

Or if you want to handle the response as a XML you should add this converter compile 'com.squareup.retrofit2:converter-jaxb:2.4.0 或者,如果您想将响应作为XML处理,则应添加此转换器compile 'com.squareup.retrofit2:converter-jaxb:2.4.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM