Java parse JSON from URL NullPointerException - java

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

Related

InputStream does not seem to read response objects in list

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

Java - Access JSON Element (llegalFormatConversionException: d !=java.lang.String)

I am trying to learn JAVA and build a plugin for Minecraft; I have been successfully able to get the JSON data from my api endpoint however, the issue I am facing right now is an llegalFormatConversionException: d !=java.lang.String which means that the format I am trying to make into string isn't equal to the type of string that it's looking for.
I am trying to access a JSON element from my endpoint called condition
{
"todaysdate": "2021-02-12",
"temperature": 25,
"description": [
"Overcast"
],
"condition": 122,
}
Coming from C#; I know there's a website called json2sharp where you can create a root class for the JSON. I'm not sure how it would be applied in Java but currently, my code looks like this.
private String fetchWeather() throws IOException, InvalidConfigurationException {
// Download
final URL url = new URL(API);
final URLConnection request = url.openConnection();
// Set HEADER
request.setRequestProperty("x-api-key", plugin.apiKey);
request.setConnectTimeout(5000);
request.setReadTimeout(5000);
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();
//JsonElement code = rootobj.get("condition");
String condition_code = rootobj.get("condition").toString();
plugin.getLogger().fine(String.format(
"[%s] Weather is %d",
world.getName(), condition_code
));
return condition_code;
}
If I call
private JsonObject fetchWeather() throws IOException, InvalidConfigurationException {
// Download
final URL url = new URL(API);
final URLConnection request = url.openConnection();
// Set HEADER
request.setRequestProperty("x-api-key", plugin.apiKey);
request.setConnectTimeout(5000);
request.setReadTimeout(5000);
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();
return rootobj;
}
state = fetchWeather();
plugin.getLogger().warning(state.toString());
I do get the actual JSON with all of the elements so I know the URL and accessing it is completely working, but I get an llegalexception for format if I try to call and print with logger the condition code.
So, if I change the return type in fetchWeather() to be the root json object and then try to print it with the state variable above it works; but if I try to return the condition json element and print it it gives me an iilegal exception.
Now before I posted this question I did read some other questions people had but I couldn't get a working solution from their suggested answers. So, I am hoping someone can point me out on what I'm doing wrong because I know I'm messing up somewhere with the variable format.
Thanks.
Line 37: state = fetchWeather();
Line 103:
plugin.getLogger().fine(String.format(
"[%s] Weather is %d",
world.getName(), bId
));
condition_code variable is String. You should use the %s format specifier.

Loop through json file appending key value to List

I am trying to loop through a JSON file and append the value each time to patientList. So far I believe I have done the hard part, however the simplest part seems to be taking a lot of time, that is appending the values to patientList. My getJsonFile method gets the path of the JSON file. The format of the JSON file is below. I am able to print jsonArray so I know I am good up to that point, but lost after that.
Json file.
[{"patient":1},{"patient":2},{"patient":3},{"patient":4},{"patient":5},{"patient":6},{"patient":7},{"patient":8},{"patient":9}]
getJsonFile method.
private List<Integer> getJsonFile(String path)
{
List<Integer> patientList = new ArrayList<>();
try (FileReader reader = new FileReader(path))
{
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray)jsonParser.parse(reader);
System.out.println(jsonArray);
// Update patientList
for (int i = 0; i < jsonArray.size(); i++ )
{
patientList.add(jsonArray(i));
}
}
catch(IOException | ParseException | NullPointerException e)
{
e.printStackTrace();
}
return patientList;
}
Your JSONArray contains objects: {"patient":1}
So you could not add patientList.add(jsonArray(i));
You have to access the int value inside that object:
JSONObject patient = jsonArray.getJsonObject(i);
patientList.add(patient.getInt("patient");
Edit
Well. You are using the simple-json library with quite limit feature and outdated. In this case you have to cast the data yourself:
JSONObject patient = (JSONObject)jsonArray.get(i);
patientList.add((Integer)patient.get("patient");
I recommend you remove this lib and use existing JSON feature of Java. If you want more advance feature, Jackson/GSon is the library to use.

way to parse my json in java

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

JAVA JSONObject parsing issue

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/

Categories