Suraj Prasad
Suraj Prasad

Reputation: 251

Get String value of json array in a json

For the below Json payload I'am trying to get the first array element of email_address. However using the below code I get email address but with the array bracket and quotes like: ["[email protected]"]. I need only the email address text. First element array.

Payload:

{
   "valid":{
      "email_addresses":[
         "[email protected]"
      ]  
   }
}

Code:

JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(jsonfilepath));
JSONObject jsonObjects = (JSONObject) parser.parse(jsonObject.get("valid").toString());
String email = jsonObjects.get("email_addresses").toString();
System.out.println("Email address:"+email);

Upvotes: 2

Views: 1785

Answers (2)

kosta.dani
kosta.dani

Reputation: 457

Maybe this unitTest could help you

   @Test
   public void test() throws JSONException, FileNotFoundException {
      JSONObject json = new JSONObject(new JSONTokener(new FileInputStream(new File(jsonfilepath))));
      JSONObject valid = (JSONObject) json.get("valid");
      Object emailAdresses = valid.get("email_addresses");
      if (emailAdresses instanceof JSONArray) {
         JSONArray emailAdressArray = (JSONArray) emailAdresses;
         Object firstEmailAdress = emailAdressArray.get(0);
         System.out.println(firstEmailAdress.toString());
      }
   }

Upvotes: 3

jeprubio
jeprubio

Reputation: 18002

You could use JSONArray to get the array values:

JSONArray emailAddresses = (JSONArray) jsonObjects.get("email_addresses");
String email = emailAddresses.getJSONObject(0).toString()
System.out.println("Email address: " + email);

Even though I strongly encourage using gson to parse json instead of doing this way, it makes life easier.

Upvotes: 4

Related Questions