【问题标题】:How to get XML response by using Retrofit in Android如何在 Android 中使用 Retrofit 获取 XML 响应
【发布时间】:2018-10-01 06:28:24
【问题描述】:

我想使用 Retrofit 解析 XML 响应,但我得到空响应 我为它的每个 xml 标签创建了模型类。我想通过使用new Gson().toJson(response.body) 在 logcat 中获取所有响应打印,就像 json 响应打印一样 来自网络服务的响应 -

<?xml version="1.0"?>
<string xmlns="http://tempuri.org/">
  <NewDataSet>
    <Table>
      <g_Vill>700</g_Vill>
      <g_Code>47751</g_Code>
      <g_adhaar_card_no>0</g_adhaar_card_no>
      <G_Mobile_Number>9616265075</G_Mobile_Number>
      <g_unique_cd>500109460194</g_unique_cd>
      <G_Name>Nirmala Devi</G_Name>
      <F_Name>Jokhan</F_Name>
      <S_Name>COOP. CANE DEVP. SOC. GHOSI. </S_Name>
      <C_Name>Karkhiya</C_Name>
      <V_Name>Roshangunj</V_Name>
      <bank>Kashi Gomati Bank Ltd</bank>
      <MD_Mode>TROLLY-GATE</MD_Mode>
      <g_bquota>149.56600</g_bquota>
      <g_TArea>0.09700</g_TArea>
      <g_accnt>111552010001742</g_accnt>
      <g_T_Bond>48.06800</g_T_Bond>
      <AvgUpaj>0</AvgUpaj>
      <crushyear>2017-2018</crushyear>
      <Branch>ChalakpurAzamgarh</Branch>
    </Table>
  </NewDataSet>
</string>

我通过XML to JavaPojo class创建了它的模型类

我得到空响应

EndPointInterface git = ApiClient.getClient().create(EndPointInterface.class);
            Call<GrowerDetailsResponse> call = git.GrowerDetails("700","47751","1819","8");
            call.enqueue(new Callback<GrowerDetailsResponse>() {

                @Override
                public void onResponse(Call<GrowerDetailsResponse> call, retrofit2.Response<GrowerDetailsResponse> response) {
                    Log.e("FundRequest", "hello response : " + response.body().getNewDataSet().getTable().getAvgUpaj());
                }

                @Override
                public void onFailure(Call<GrowerDetailsResponse> call, Throwable t) {
                    Log.e("response", "error "+t.getMessage());

                }
            });

【问题讨论】:

    标签: android xml retrofit retrofit2 simple-framework


    【解决方案1】:

    你需要像这样添加转换器工厂方法:

    Retrofit retrofit = new Retrofit.Builder()  
                      .baseUrl(API_BASE_URL)
        .client(new OkHttpClient())
        .addConverterFactory(SimpleXmlConverterFactory.create())
        .build();
    

    还需要将这些行添加到gradle

     compile 'com.squareup.retrofit2:converter-simplexml:2.3.0'
    

    参考访问:https://futurestud.io/tutorials/retrofit-how-to-integrate-xml-converter

    【讨论】:

    • 您的响应是空的还是您用于 logcat (response.body().getNewDataSet().getTable().getAvgUpaj()) 的行?
    • 是的,我在使用 response.body().getNewDataSet().getTable().getAvgUpaj() 时得到空响应
    • 我使用了你的 xml 到 pojo 转换器,发现它没有提供所需的 pojo。你能把你正在使用的pojo贴出来吗?还有一些标签需要在变量上方声明。
    • 复制我的回复并通过 [link] (pojo.sodhanalibrary.com) 生成 pojo 类
    • 您将不得不使用@Root 等标签,就像我们将 json 转换为 java 类一样。请参考我上面提供的链接。
    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多