Search code examples
javaandroidjsonretrofit

How to use json object that contains more json object


I am new to the calling API. I am calling API using Retrofit in Java. Sometimes I get that type of object.

{
  "error": 0,
  "msg": "Success",
  "data": {
    "request_id": 0000,
    "request_status": "Complete",
    "request_charge": "0.0000",
    "recipients": [
      {
        "number": "8801800000000",
        "charge": "0.0000",
        "status": "Sent"
      }
    ]
  }
}

In this JSON how can I use "mag", the data object, and also use the recipients object.

I need the string value of mag, request_status, number, and status.

How can I do this?


Solution

  • In plain Javascript, if you have the above JSON object as a JSON string in a variable called myJson, just use JSON.parse to convert it into a JS object:

    let myObject = JSON.parse(myJson);
    

    If the JSON object is not a string, but already a JS object, skip the above.

    Then simply access the properties of the object:

    console.log(myObject.msg);  // "Success"
    console.log(myObject.data.recipients[2]);  // "Sent"