【问题标题】:How to parse Json using Retrofit if key is inside of another object如果键在另一个对象内,如何使用 Retrofit 解析 Json
【发布时间】:2018-04-25 22:30:05
【问题描述】:

任何人都可以帮助我使用改造来解析下面的 json 吗?

{
  "key1": "value",
  "key2": {
           "key3": "value2",
           "key4": "some random text is here"
          },
  "value2" : {
               -- actual data is here ---
             }
}

这里的“value2”会改变。我无法弄清楚如何获取“Key3”的值并使用 Retrofit 获取实际数据。
提前致谢。

【问题讨论】:

标签: android retrofit jsonparser


【解决方案1】:

您可以将 json 数据放入 pojo 类中,将您的 json 数据放在下面的网站中,它会生成 pojo 类..

http://www.jsonschema2pojo.org/

将以下依赖项添加到应用级 gradle 文件中 ..

    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

然后当你让改造对象通过这条线之后..

 retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

【讨论】:

    【解决方案2】:

    你可以这样做,假设你有 JSONObject 和上面提到的 json。

    你可以像String value = jsonObject.optString("key1");一样解析它

    【讨论】:

      【解决方案3】:

      试试这个:

      try {
              JSONObject jsonObject = new JSONObject("Your_json_string");
              String key1 = jsonObject.optString("key1");
              JSONObject key2 = jsonObject.optJSONObject("key2");
      
              String value2 = key2.optString("key3");//It will get value
      
              JSONObject jsonObjectValue2 = jsonObject.optJSONObject(value2);// now use value2 here for actual result
              String finalValue = jsonObjectValue2.optString("next_value");
              //....and so on
      
          } catch (JSONException e) {
              e.printStackTrace();
          }
      

      【讨论】:

        【解决方案4】:

        Retrofit 支持converterFactory,你可以试试Gson 或者Jackson

        在下面找到一个例子

        在gradle中添加依赖,

        implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
        

        Java 代码

         new Retrofit.Builder().baseUrl(BuildConfig.BASE_URL).
                    addConverterFactory(GsonConverterFactory.create()).
                    client(okHttpClient).
                    build();
        
         public interface GetAllAPI {
                @GET("/all")
                List<Country> getCountries();
            }
        

        【讨论】:

          猜你喜欢
          • 2015-09-12
          • 1970-01-01
          • 2021-02-03
          • 2021-05-19
          • 2015-11-08
          • 1970-01-01
          • 2020-04-02
          • 2018-05-31
          • 2016-01-01
          相关资源
          最近更新 更多