Get String value of json array in a json

Suraj Prasad :

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334657&siteId=1