RECORRER JSONOBJECT, ANDROID

1

I need to take the values that are within REGION

"addresses":[{
            "id":2,
            "customer_id":2,
                "region":{
                    "region_code":"NY",
                    "region":"New York",
                    "region_id":43
                    },
                "region_id":43,
                "country_id":"US",
                    "street":[
                                "123 Oak Ave"
                            ],
                "telephone":"512-555-1111",
                "postcode":"10755",
                "city":"Purchase",
                "firstname":"Henry",
                "lastname":"Arcila",
                "default_shipping":true,
                "default_billing":true
        }],
    
asked by Andrea Valentina 12.12.2018 в 13:42
source

2 answers

0

aderesses is a JSONArray you must go through them to access their elements:

JSONArray jsonArray = json.getJSONArray("addresses");
JSONObject jsonRegion;
String region_code = "";
String region = "";
int region_id = 0;


for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jo = jsonArray.getJSONObject(i);
    jsonRegion = jo.getJSONObject("region");
    region_code = jsonRegion.getString("region_code");
    region =jsonRegion.getString("region");
    region_id= jsonRegion.getInt("region_id");
}
    
answered by 12.12.2018 / 16:38
source
1

I do not see which is the complete tree of that object so I give you a solution based on what you have asked.

If you remove the object addresses[0] from a variable and start parsing it to JSON you have to follow these steps:

String region_code = "";
String region = "";
int region_id = 0;

try {
    JSONObject reader = new JSONObject(obj);
    JSONObject region= reader.getJSONObject("region");
    region_code = region.getString("region_code");
    region = region.getString("region");
    region_id = region.getInt("region_id");
} catch (JSONException e) {
    e.printStackTrace();
}

Probably the object is longer and you have to perform the parsing of the whole object until you reach this point, but it would be to repeat the actions from the root of the object.

    
answered by 12.12.2018 в 15:16