-2

Here's the JSON:

{
    "firstName": "John",
    "lastName": "doe",
    "age": 26,
    "address": {
        "streetAddress": "123 Main street",
        "city": "Anytown",
        "postalCode": "12345"
    },
    "phoneNumbers": [
        {
            "type": "iPhone",
            "number": "123-456-8888"
        },
        {
            "type": "home",
            "number": "123-557-8910"
        }
    ]
}

The question is, in Java, how do you access the address fields? I tried things like address.city, but that didn't work:

String city = (String) jsonObject.get("address.streetAddress");
System.out.println(city);

Would appreciate any suggestions.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Morkus
  • 517
  • 7
  • 21

3 Answers3

0

You need to call getString on the address object that you get.

String city = jsonObject.getJSONObject("address").getString("streetAddress");
mittmemo
  • 2,062
  • 3
  • 20
  • 27
0
{
    "firstName": "John",
    "lastName": "doe",
    "age": 26,
    "address": {
        "streetAddress": "123 Main street",
        "city": "Anytown",
        "postalCode": "12345"
    },
    "phoneNumbers": [
        {
            "type": "iPhone",
            "number": "123-456-8888"
        },
        {
            "type": "home",
            "number": "123-557-8910"
        }
    ]
}

first get your address.Address is an object.{} means object,[] means an array.

JSONObject addressObj = jsonObject.get("address");

now you have a reference to the address.

String addressStr = addressObj.get("streetAddress");
String cityStr = addressObj.get("city");
int cityInt = Integer.parseInt(addressObj.get("postalCode"));

If i don't wrong remember there should be getString("streetAddress") and getInteger("postalCode") to avoid parse issues.

Jason
  • 11,744
  • 3
  • 42
  • 46
Sarkhan
  • 1,281
  • 1
  • 11
  • 33
0

Apart from the given answers you should add a check to see if the address is not blank before checking city or else you will end up getting and exception. Here is updated example:

if( jsonObject.has("address"){
    JSONObject addressObj = jsonObject.get("address");

    if( addressObj.has("city"){
        String cityStr = addressObj.get("city");
    }
}
Jason
  • 11,744
  • 3
  • 42
  • 46
Amit Mahajan
  • 895
  • 6
  • 34