2

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);

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Why are you parsing json string to json, just to convert it back to string to parse it again? parser.parse(jsonObject.get("valid").toString())
@rkosegi well, that part it's not the code I changed. It was in the question. But yes, it makes no sense, I'll update it
then don't put it in an answer. It's non-sense
Ok, I'll only put in the answer the code to add / update
3

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());
      }
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.