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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With