-3

I want to get fullname including title, first and last and city value from the location in xml file. I mean correct path. Can you help with this code. Thank you.

            JSONObject object = new JSONObject(s);
            JSONArray array = object.optJSONArray("results");

            for (int i = 0; i < array.length(); i++) {

                JSONObject jsonObject = array.optJSONObject(i);
                
                String Name = jsonObject.optString("name");
                String City = jsonObject.optString("location");
                String Email = jsonObject.optString("email");
                String Phone = jsonObject.optString("phone");

                testModel model = new testModel();
                
                model.setFullname(Name);
                model.setCity(City);
                model.setEmail(Email);
                model.setPhone(Phone);
                arrayList.add(model);

JSON response:

{"results":[{"name":{"title":"Mrs","first":"Elsa","last":"Sanchez"},"location":{"street":{"number":8890,"name":"Rue Dumenge"},"city":"Pau","state":"Ardèche","country":"France","postcode":61036,"coordinates":{"latitude":"-3.4635","longitude":"168.2515"},"timezone":{"offset":"0:00","description":"Western Europe Time, London, Lisbon, Casablanca"}},"email":"elsa.sanchez@example.com","phone":"02-24-50-09-33","picture":{"large":"https://randomuser.me/api/portraits/women/39.jpg","medium":"https://randomuser.me/api/portraits/med/women/39.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/39.jpg"}}],"info":{"seed":"3060b5a6b7ff6a03","results":1,"page":1,"version":"1.3"}}
Stelios Papamichail
  • 955
  • 2
  • 19
  • 57
The Ark D
  • 7
  • 4
  • Please post the JSON within the post instead of linking to an image of it :) – Stelios Papamichail Jun 18 '21 at 22:45
  • Okay, I posted the json; you can find it here : https://randomuser.me/api/?inc=name,location,email,phone,picture – The Ark D Jun 18 '21 at 22:53
  • Any code in any post you make should be embedded within the post. You should avoid using links or images to point to code snippets. Instead, add them directly in your post so that people can copy and edit them easily. – Stelios Papamichail Jun 18 '21 at 22:55

1 Answers1

0

Here's a sample of how to get the street field from your response:

try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray results = jsonObject.getJSONArray("results");
        for (int i = 0; i < results.length(); i++) {
            JSONObject jo = results.getJSONObject(i);
            JSONObject location = jo.getJSONObject("location");
            String street= location.optString("street");
        }
} catch (JSONException e) {
        e.printStackTrace();
}

You should probably add a check on whether or not the key of the current JSONObject within the loop is the "location" key you're looking for!

Stelios Papamichail
  • 955
  • 2
  • 19
  • 57