0

Can anyone help me in parsing below json using retrofit?

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

here "value2" will change. i'm not able to figure how to get the value of "Key3" and get the actual data using Retrofit.
Thanks in advance.

Raviteja
  • 86
  • 8

4 Answers4

2

you can json data into pojo class put in your json data in below website it generate pojo class..

http://www.jsonschema2pojo.org/

add below dependency into app level gradle file ..

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

then after when you make retrofit object pass this line ..

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

You can do it like this, lets say you have JSONObject with above mentioned json.

You can parse it like String value = jsonObject.optString("key1");

Ahmad Ayyaz
  • 774
  • 8
  • 25
-1

Retrofit supports converterFactory, you can try Gson or Jackson with it

Find an example below

Add dependency in gradle,

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

Java Code

 new Retrofit.Builder().baseUrl(BuildConfig.BASE_URL).
            addConverterFactory(GsonConverterFactory.create()).
            client(okHttpClient).
            build();

 public interface GetAllAPI {
        @GET("/all")
        List<Country> getCountries();
    }
Sreedhu Madhu
  • 2,480
  • 2
  • 30
  • 40
-1

Try out this:

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();
    }
immodi
  • 607
  • 1
  • 6
  • 21