Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve just one field from JSON string in Java

Tags:

java

json

object

Is there a way to just one field from the JSON string? My code is as follows:

Object obj = parser.parse(resp);
System.out.println(obj);
JSONArray array = new JSONArray();
array.add(obj);

JSONObject obj2 = (JSONObject)array.get(0); //Getting NPE here
//Object obj3 = obj2.get("data");

System.out.println("Data: " + obj2.get("data"));
//System.out.println("Email: " + obj3.get("email_address"));    

I'm using the following libraries

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;

From the response string resp, I just need data.email_address. I am unable to find a way to do it.

like image 982
p0tta Avatar asked Dec 18 '22 08:12

p0tta


1 Answers

So if this is your input:

{
    "data": {
        "email_address": "[email protected]"
    }
}

You first will need to make it a JSONObject:

JSONObject object = (JSONObject) new JSONParser().parse(json);

And then you can get data, another JSONObject:

JSONObject data = (JSONObject) object.get("data")

And from your data Object you can get email_address:

String email = data.get("email_address").toString();

If your input is an array of users, like this:

{
  "users": [
    {
      "data": {
        "email_address": "[email protected]"
      }
    },
    {
      "data": {
        "email_address": "[email protected]"
      }
    }
    ]
}

You can get it the same way:

JSONObject object = (JSONObject) new JSONParser().parse(json);
JSONArray users = (JSONArray) object.get("users");
JSONObject user0 = (JSONObject) users.get(0);
JSONObject user0data = (JSONObject) user0.get("data");
String email = user0data.get("email_address").toString();

First parse the whole JSON into an Object. Then get an array called users, from that array, get index 0. From that Object, get data, and then email_address

like image 84
Lóránt Viktor Gerber Avatar answered Dec 28 '22 07:12

Lóránt Viktor Gerber