I am trying to read a response from an API endpoint. It works in Postman and appears to work when debugging my java code.
However it will not read any objects that are in the nested array.
I've followed this solution (in the comments someone lays out their solution to accessing objects in a nested array) yet that does not seem to have solved anything as the mapper consistently shows nothing inside the json list.
Here's my code:
try {
response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(inputStream);
final JsonNode value = node.get("value");
final JsonNode index = value.get(1);
final String status = index.get("status").asText();
return status;`
}
Here's the response that I'm trying to unpack. I'm trying to get the value of "status"
{
"value": [
{
"activityRunEnd": "2023-01-23T23:22:01.4234985Z",
},
{
"status": "Succeeded"
}
]
}
This is the response that I'm currently getting when I readTree(inputStream)
{"value":[]}
InputStream does not seem to read any values inside the list
I'm trying to parse the JSON from the following API:
https://opentdb.com/api.php?amount=1
but when I'm trying to get the question value, I get the following error:
Exception in thread "main" java.lang.NullPointerException
I use this code:
public static void main(String[] args) throws IOException {
String question;
String sURL = "https://opentdb.com/api.php?amount=1"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
question = rootobj.get("question").getAsString(); //grab the question
}
Hope someone can tell me what I am doing wrong.
Thanks in advance!
When I look at the JSON you are trying to interpret, I get:
{
"response_code": 0,
"results":[
{
"category": "Entertainment: Board Games",
"type": "multiple",
"difficulty": "medium",
"question": "Who is the main character in the VHS tape included in the board game Nightmare?",
"correct_answer": "The Gatekeeper",
"incorrect_answers":["The Kryptkeeper","The Monster","The Nightmare"]
}
]
}
This JSON doesn't contain a root member "question". This makes rootobj.get("question") return null, and therefore calling getAsString on it throws the NullPointerException.
So instead of rootobj.get("question"), you would have to walk through the hierarchy: "results" -> first array member -> "question":
rootobj.getAsJsonArray("result").getAsJsonObject(0).get("question")
Try this one
question = rootobj.getAsJsonArray("results").get(0).getAsJsonObject().get("question").getAsString();
The JSON has no direct "question" field.
call question = rootobj.get("result").get(0).get("question").getAsString(); instead
I want to parse my json string at run time. But, the problem is my json string is not a valid one due to some issues. Is there any way to parse the json with validation. My json string looks like this:
{"page_1":"{\"city\":\"Delhi\",\"locality\":\"Alaknanda\",\"Name_of_Person\":\"Varun Patil\",\"User_email_address\":\"varun.vap#gmail.com\",\"user_phone_number\":\"\",\"sub_locality\":\"\",\"street_name\":\"Pune\",\"home_plot_no\":\"xyz\",\"pin_code\":\"411060\",\"project_society_build_name\":\"\",\"landmark_reference_1\":\"\",\"landmark_reference_2\":\"\",\"No_of_Schools\":20,\"No_of_Hospitals\":20,\"No_of_Metro\":0,\"No_of_Mall\":20,\"No_of_Park\":20,\"Distance_of_schools\":1.51,\"Distance_of_Hospitals\":2.5,\"Distance_of_Metro\":0,\"Distance_of_Mall\":1.9,\"Distance_of_Park\":1.1,\"lat\":28.5304408,\"lng\":77.2505733,\"ipinfo\":{\"ip\":\"59.88.97.45\",\"hostname\":\"No Hostname\",\"city\":\"Pune\",\"region\":\"Maharashtra\",\"country\":\"IN\",\"loc\":\"18.5333,73.8667\",\"org\":\"AS9829 National Internet Backbone\",\"postal\":\"411001\"}}","page_2":"{\"home_type\":\"Flat\",\"area\":\"1000\",\"beds\":\"2 BHK\",\"bath_rooms\":2,\"building_age\":\"3\",\"floors\":\"\",\"balcony\":1,\"amenities\":\"regular\",\"amenities_options\":{\"gated_security\":\"\",\"physical_security\":\"\",\"cctv_camera\":\"\",\"controll_access\":\"\",\"elevator\":\"\",\"power_back_up\":\"\",\"parking\":\"\",\"partial_parking\":\"\",\"onsite_maintenance_store\":\"\",\"open_garden\":\"\",\"party_lawn\":\"\",\"amenities_balcony\":\"\",\"club_house\":\"\",\"fitness_center\":\"\",\"swimming_pool\":\"\",\"party_hall\":\"\",\"tennis_court\":\"\",\"basket_ball_court\":\"\",\"squash_coutry\":\"\",\"amphi_theatre\":\"\",\"business_center\":\"\",\"jogging_track\":\"\",\"convinience_store\":\"\",\"guest_rooms\":\"\"},\"interior\":\"regular\",\"interior_options\":{\"tiles\":\"\",\"marble\":\"\",\"wooden\":\"\",\"modular_kitchen\":\"\",\"partial_modular_kitchen\":\"\",\"gas_pipe\":\"\",\"intercom_system\":\"\",\"air_conditioning\":\"\",\"partial_air_conditioning\":\"\",\"wardrobe\":\"\",\"sanitation_fixtures\":\"\",\"false_ceiling\":\"\",\"partial_false_ceiling\":\"\",\"recessed_lighting\":\"\"},\"location\":\"regular\",\"location_options\":{\"good_view\":\"\",\"transporation_hub\":\"\",\"shopping_center\":\"\",\"hospital\":\"\",\"school\":\"\",\"ample_parking\":\"\",\"park\":\"\",\"temple\":\"\",\"bank\":\"\",\"less_congestion\":\"\",\"less_pollution\":\"\"},\"maintenance\":\"\",\"maintenance_value\":\"\",\"near_by\":{\"school\":\"\",\"hospital\":\"\",\"mall\":\"\",\"park\":\"\",\"metro\":\"\"},\"city\":\"Delhi\",\"locality\":\"Alaknanda\",\"token\":\"9a2a8bf359494054f98c80009b5bd0e7\"}"}
I tried the following methods:
String result = java.net.URLDecoder.decode(jsonstring, "UTF-8");
String withCharacters = StringEscapeUtils.unescapeHtml(jsonstring);
JSONObject json = (JSONObject)new JSONParser().parse(jsonstring);
System.out.println("city=" + json.get("city"));
System.out.println("locality=" + json.get("locality"));
Nothing works for me and any help will be appreciated.
You have some escaped json inside your main json structure. That means it's valid json, but after parsing the main structure you have to parse the value of page_1 (and probably all remaining pages as well). Try this:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)parser.parse(jsonstring);
JSONObject nestedJson = (JSONObject)parser.parse(json.get("page_1"));
System.out.println("city=" + nestedJson.get("city"));
I am putting some java objects in the Json at server side
like this :
ArrayList<VisjsNode>visjsNodes = new ArrayList<VisjsNode>();
ArrayList<VisjsConnection> visjsConnections = new ArrayList<VisjsConnection>();
String jsondata = null;
org.json.JSONObject object = new org.json.JSONObject();
try {
object.put("nodes", visjsNodes);
object.put("connections", visjsConnections);
jsondata = object.toString();
Now is there a way I can get these objects back from this json (jsondata) at client side
I am doing this:
com.google.gwt.json.client.JSONValue jsonValue = JSONParser.parseStrict(jsondata);
com.google.gwt.json.client.JSONObject jsonObject = jsonValue.isObject();
jsonValue = jsonObject.get("nodes");
Now I am trying this to get ArrayList back , by doing this
ArrayList<VisjsNode>visjsNodesFromjson = jsonValue ;
But its not compiling ,it says Incompatable types...
Can you please guide how we can retrieve the Java Object back from Json ..
That's because you're using two different JsonObject class. First you use the one which comes from org.json (org.json.JsonObject) and the other is com.google.gwt.json.client.JSONObject. Nevertheless, they're named similar, they're completely different classes.
I am using JSONObject to parse nested JSON from an API example:
{"results":[{"congress":"112","state":"NJ","num_results":"2","offset":"0","members": [{"id":"L000123","first_name":"Frank"..........................
I am having trouble accessing the members nested area using JSONObject.
This is my code, any thoughts?
url= new URL("http://api.nytimes.com/svc/politics/v3/us/legislative/congress/112/senate/members.json?&state=NJ&api-key=7967107ef3c9e8d6c2f560027f87904e:17:65990356");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(url.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();
// parse the JSON object returned
JSONObject jsonO = new JSONObject(urlContents);
System.out.println(jsonO.toString());
JSONObject results = jsonO.getJSONObject("results");
JSONObject senators = results.getJSONObject("members");
You should use third party library like GSON.
http://code.google.com/p/google-gson/