Home > Enterprise >  How do I extract exact value from Json
How do I extract exact value from Json

Time:07-30

Below Json I want to get only first mail value ([email protected]) 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": [
          "[email protected]",
          "[email protected]"
        ]
      }
    }
  ]
}

CodePudding user response:

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\":[\"[email protected]\",\"[email protected]\"]}}]}";
        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

CodePudding user response:

I can able to get mail by using below code

//root = my json
JsonObject rootobj = root.getAsJsonObject();
JsonArray profilesItems = rootobj.getAsJsonArray("profiles");
JsonObject firstValue = profilesItems.get(0).getAsJsonObject().getAsJsonObject("content");
JsonElement emails = firstValue.get("mail");
String mail = emails.getAsJsonArray().get(0).getAsString();
  • Related