Below Json I want to get only first mail value (abc@test.com) using java. Please anybody can suggest how do I extract exact value from below Json. Thanks in advance.
{ "profiles": [ { "userId": "1234", "content": { "address": { "business": { "country": "IN", "locality": "Chennai", } }, "name": { "first": "abc", "last": "abc" }, "mail": [ "abc@test.com", "xyz@test.com" ] } } ] }
Advertisement
Answer
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Test { public static void main(String[] args) throws JSONException { String jsonstring = "{"profiles":[{"userId":"1234","content":{"address":{"business":{"country":"IN","locality":"Chennai"}},"name":{"first":"abc","last":"abc"},"mail":["abc@test.com","xyz@test.com"]}}]}"; System.out.println(jsonstring); JSONObject jsonObject = new JSONObject(jsonstring); JSONArray profiles = jsonObject.getJSONArray("profiles"); for (int i = 0; i < profiles.length(); i++) { JSONObject curProfile= (JSONObject) profiles.get(i); JSONArray mails= (JSONArray)((JSONObject)curProfile.get("content")).get("mail"); System.out.println(mails.get(0)); } } }
as they have already said json standard doesn’t impose ordering, so be careful