-1

I want to parse Json object using Retrofit. What is the best way to parse "Phone" and "Address"? Thank you.

{
    "name": "Miss Piggy",
    "id": "13",
    "companyName": "Muppets, Baby",
    "isFavorite": false,
    "smallImageURL": "https://s3.amazonaws.com/technical-challenge/v3/images/miss-piggy-small.jpg",
    "largeImageURL": "https://s3.amazonaws.com/technical-challenge/v3/images/miss-piggy-large.jpg",
    "emailAddress": "Miss.Piggy@muppetsbaby.com",
    "birthdate": "1987-05-11",
    "phone": {
        "work": "602-225-9543",
        "home": "602-225-9188",
        "mobile": ""
    },
    "address": {
        "street": "3530 E Washington St",
        "city": "Phoenix",
        "state": "AZ",
        "country": "US",
        "zipCode": "85034"
    }
}
Rahul Shyokand
  • 1,255
  • 10
  • 17
  • 1
    Does this answer your question? [Get nested JSON object with GSON using retrofit](https://stackoverflow.com/questions/23070298/get-nested-json-object-with-gson-using-retrofit) – fdermishin Dec 08 '20 at 08:54

2 Answers2

1

You could use a JSON parsing library (such as Gson or Moshi) with the correct retrofit converter in order to create classes (data classes in kotlin) for parsing the embed objects.

An example in kotlin.

Response class

data class Response (
    val name: String,
    val id: String,
    val companyName: String,
    val isFavorite: Boolean,
    val smallImageURL: String,
    val largeImageURL: String,
    val emailAddress: String,
    val birthdate: String,
    val phone: Phone,
    val address: Address) 

Address Class

data class Address (
    val street: String,
    val city: String,
    val state: String,
    val country: String,
    val zipCode: String )

Phone Class

data class Phone (
    val work: String,
    val home: String,
    val mobile: String)

For more details take a look in Google's Codelab example

frontz
  • 101
  • 7
1

If you plan to get the value of any string from any sub JSON object then using Android JAVA's built-in JSON parsers can help you without any new library.

JSONObject jsonObject = new JSONObject(s);
// extract phone object
JSONObject phoneJsonObject = jsonObject.getJSONObject("phone");
// we can any data of the sub json object of main object
// get string value of work
String valueOfWork = phoneJsonObject.getString("work");

// extract address object
JSONObject addressJsonObject = jsonObject.getJSONObject("address");
// we can any data of the sub json object of main object
// get string value of street
String valueOfStreet = phoneJsonObject.getString("street");

Log.i("Getting Value of Work from Phone Object", valueOfWork);
Log.i("Getting Value of Street from Address Object", valueOfStreet);
fdermishin
  • 3,519
  • 3
  • 24
  • 45
Rahul Shyokand
  • 1,255
  • 10
  • 17