This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm learning java recently and when I wanted to parse the data from a weather website, I got this error and I still can't figure it out, can anybody tell why I got this error: java.lang.NullPointerException ?
public class main {
public static void main(String []args) {
try {
URL url = new URL("http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=caa2f68a7b2b43a09c115021171404&format=json&q=atlanta&date=2015-07-20&tp=24");
InputStream is = url.openStream();
JsonReader rdr = Json.createReader(is);
JsonObject obj = rdr.readObject();
JsonArray data = obj.getJsonArray("weather");
JsonObject objectOfData = data.getJsonObject(0);
System.out.println(objectOfData.getString("date"));
} catch (Exception ex){
System.out.println(ex);
}
}
}
Here is the data parsed from Postman:
Here is the trace log:
Here is the picture of line 19
You may print the stack trace in the catch method, and find on which line there is error and act accordingly.
Part 1: Error with Callback
I checked your URL in my browser and it appears you have the callback parameter set to wrap the json with a request callback which looks like this:
request({"data": .... })
The parser is getting hung up on the first character which it doesn't recognize as proper json.
Try this URL instead:
http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=caa2f68a7b2b43a09c115021171404&format=json&q=atlanta&date=2015-07-20&tp=24
Part 2: Null Pointer Exception
The json is being parsed out of order. You needed to create an object from the root element "data" before accessing the array.
try {
URL url = new URL("http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=caa2f68a7b2b43a09c115021171404&format=json&q=atlanta&date=2015-07-20&tp=24");
InputStream is = url.openStream();
JsonReader rdr = Json.createReader(is);
JsonObject obj = rdr.readObject();
JsonObject objectOfData = (JsonObject) obj.get("data");
JsonArray data = objectOfData.getJsonArray("weather");
JsonObject a = data.getJsonObject(0);
System.out.println(a.getString("date"));
} catch (Exception ex){
System.out.println(ex);
}
Related
This question already has answers here:
How to check if a JSON key exists?
(13 answers)
Closed 5 years ago.
Let say this is my JSON Object
{
"LabelData": {
"slogan": "AWAKEN YOUR SENSES",
"jobsearch": "JOB SEARCH",
"contact": "CONTACT",
"video": "ENCHANTING BEACHSCAPES",
"createprofile": "CREATE PROFILE"
}
}
I need to know that either 'video` exists or not in this Object, and if it exists i need to get the value of this key. I have tried following, but i am unable to get value of this key.
containerObject= new JSONObject(container);
if(containerObject.hasKey("video")){
//get Value of video
}
Use below code to find key is exist or not in JsonObject. has("key") method is used to find keys in JsonObject.
containerObject = new JSONObject(container);
//has method
if (containerObject.has("video")) {
//get Value of video
String video = containerObject.optString("video");
}
If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject.
Use:
if (containerObject.has("video")) {
//get value of video
}
From the structure of your source Object, I would try:
containerObject= new JSONObject(container);
if(containerObject.has("LabelData")){
JSONObject innerObject = containerObject.getJSONObject("LabelData");
if(innerObject.has("video")){
//Do with video
}
}
Please try this one..
JSONObject jsonObject= null;
try {
jsonObject = new JSONObject("result........");
String labelDataString=jsonObject.getString("LabelData");
JSONObject labelDataJson= null;
labelDataJson= new JSONObject(labelDataString);
if(labelDataJson.has("video")&&labelDataJson.getString("video")!=null){
String video=labelDataJson.getString("video");
}
} catch (JSONException e) {
e.printStackTrace();
}
containerObject = new JSONObject(container);
if (containerObject.has("video")) {
//get Value of video
}
Try
private boolean hasKey(JSONObject jsonObject, String key) {
return jsonObject != null && jsonObject.has(key);
}
try {
JSONObject jsonObject = new JSONObject(yourJson);
if (hasKey(jsonObject, "labelData")) {
JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
if (hasKey(labelDataJson, "video")) {
String video = labelDataJson.getString("video");
}
}
} catch (JSONException e) {
}
JSONObject class has a method named "has".
Returns true if this object has a mapping for name. The mapping may be NULL.
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
JSONObject root= new JSONObject();
JSONObject container= root.getJSONObject("LabelData");
try{
//if key will not be available put it in the try catch block your program
will work without error
String Video=container.getString("video");
}
catch(JsonException e){
if key will not be there then this block will execute
}
if(video!=null || !video.isEmpty){
//get Value of video
}else{
//other vise leave it
}
i think this might help you
I am developing a java program which can retrieve certain data in my JSON data structure from web URL.
Here is my Json data:
{
"data_id":"a71a3c2588c6472bb4daea41a0b58835",
"file_info":{
"display_name":"",
"file_size":242,
"file_type":"Not available",
"file_type_description":"Not available",
"md5":"aa69ba384f22d0dc0551ace2fbb9ad55",
"sha1":"09ceb54e65df3d3086b222e8643acffe451a6e8a",
"sha256":"dcb46d6ae2a187f789c12f19c44bbe4b9a43bd200a3b306d5e9c1fcf811dc430",
"upload_timestamp":"2016-11-18T09:09:08.390Z"
},
"process_info":{
"blocked_reason":"",
"file_type_skipped_scan":false,
"post_processing":{
"actions_failed":"",
"actions_ran":"",
"converted_destination":"",
"converted_to":"",
"copy_move_destination":""
},
"profile":"File scan",
"progress_percentage":100,
"result":"Allowed",
"user_agent":""
},
"scan_results":{
"data_id":"a71a3c2588c6472bb4daea41a0b58835",
"progress_percentage":100,
"scan_all_result_a":"No Threat Detected",
"scan_all_result_i":0,
"scan_details":{
"Ahnlab":{
"def_time":"2016-11-08T15:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":1,
"threat_found":""
},
"Avira":{
"def_time":"2016-11-08T00:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":133,
"threat_found":""
},
"ClamAV":{
"def_time":"2016-11-08T10:28:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":94,
"threat_found":""
},
"ESET":{
"def_time":"2016-11-08T00:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":38,
"threat_found":""
}
},
"start_time":"2016-11-18T09:09:08.405Z",
"total_avs":4,
"total_time":250
},
"vulnerability_info":{
}
}
But the only data, I want is scan_all_result_i which belong to scan_results array but I am encountering some problem on it.Ii searched some information in Oracle website and it's showing that my code might be correct(reference 1 and reference 2)
The error still show up for the portion. How I handle the JSON data using JsonReader, JSONObject and JSONArray. Anyone here can guide me on how to the Json data processing? I've been figuring out this for few day and haven't any idea on it now.
Here is my java source
public class FetchResult {
public static void main(String[] args) throws IOException, JSONException {
URL theUrl = new URL ("http://192.168.0.25:8008/file/a71a3c2588c6472bb4daea41a0b58835");
HttpURLConnection con = (HttpURLConnection) theUrl.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
if(responseCode == 200)
{
try
{
InputStream is = theUrl.openStream();
JsonReader read = JsonReader.createReader(is);
JSONObject obj = read.readObject();
JSONArray result = obj.getJSONArray("scan_results");
For(JSONObject result : result.getValueAs(JSON.Object.class))
{
System.out.print(result.getString("scan_all_result_i"));
}
// JSONObject obj = new JSONObject ();
// obj.getJsonObject("scan_results");
// System.out.println(obj.toString());
}
catch(MalformedURLException e)
{
System.out.print("your problem here ...1");
}
}
else
{
System.out.print("Can't Connect");
}
}
The error message, I got in my eclipse compiler
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method createReader(InputStream) is undefined for the type JsonReader
Type mismatch: cannot convert from JsonObject to JSONObject
Syntax error on token "JSONObject", ? expected after this token
JSONObject cannot be resolved to a variable
The method getValueAs(Class) is undefined for the type JSONArray
JSON cannot be resolved to a type
Syntax error, insert ";" to complete Statement
The method getString(int) in the type JSONArray is not applicable for the arguments (String)
At for loop, it should be
for (Object obj : result) {
JSONObject jsonObj = (JSONObject) obj;
System.out.print(jsonObj.getString("scan_all_result_i"));
}
The API for an app I'm currently working on uses JSON as a main way of communicating data - including error messages in failed response scenario (response code != 2xx).
I'm migrating my project to use Square's OkHttp networking library. But am having difficulties to parse said error messages. For OkHttp's response.body().string(), apparently, only returns request code "explanation" (Bad Request, Forbidden, etc) instead of the "real" body content (in my case: a JSON describing the error).
How to get the real response body instead? Is this even possible when using OkHttp?
As an illustration, here's my method for parsing JSON response:
private JSONObject parseResponseOrThrow(Response response) throws IOException, ApiException {
try {
// In error scenarios, this would just be "Bad Request"
// rather than an actual JSON.
String string = response.body().toString();
JSONObject jsonObject = new JSONObject(response.body().toString());
// If the response JSON has "error" in it, then this is an error message..
if (jsonObject.has("error")) {
String errorMessage = jsonObject.get("error_description").toString();
throw new ApiException(errorMessage);
// Else, this is a valid response object. Return it.
} else {
return jsonObject;
}
} catch (JSONException e) {
throw new IOException("Error parsing JSON from response.");
}
}
I feel dumb. I know now why above code won't work:
// These..
String string = response.body().toString();
JSONObject jsonObject = new JSONObject(response.body().toString());
// Should've been these..
String string = response.body().string();
JSONObject jsonObject = new JSONObject(response.body().string());
TL;DR It should've been string() and not toString().
I am coding in Java and I'm using the minimal-json library. I am trying to get some information from a json text (idk if it's an array).
I'm trying to access the "game" value inside "stream", but I always get a crash by nullpointer or a parseexception.
Here is the json string I'm trying to get (From the Twitch Api):
{"_links":{"self":"https://api.twitch.tv/kraken/streams/hackerc0w","channel":"https://api.twitch.tv/kraken/channels/hackerc0w"},"stream":{"_id":13817896816,"game":"Programming","viewers":13,"created_at":"2015-04-01T13:54:54Z","video_height":1080,"average_fps":59.9235368156,"_links":{"self":"https://api.twitch.tv/kraken/streams/hackerc0w"},"preview":{"small":"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-80x45.jpg","medium":"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-320x180.jpg","large":"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-640x360.jpg","template":"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-{width}x{height}.jpg"},"channel":{"_links":{"self":"https://api.twitch.tv/kraken/channels/hackerc0w","follows":"https://api.twitch.tv/kraken/channels/hackerc0w/follows","commercial":"https://api.twitch.tv/kraken/channels/hackerc0w/commercial","stream_key":"https://api.twitch.tv/kraken/channels/hackerc0w/stream_key","chat":"https://api.twitch.tv/kraken/chat/hackerc0w","features":"https://api.twitch.tv/kraken/channels/hackerc0w/features","subscriptions":"https://api.twitch.tv/kraken/channels/hackerc0w/subscriptions","editors":"https://api.twitch.tv/kraken/channels/hackerc0w/editors","videos":"https://api.twitch.tv/kraken/channels/hackerc0w/videos","teams":"https://api.twitch.tv/kraken/channels/hackerc0w/teams"},"background":null,"banner":null,"broadcaster_language":"en","display_name":"hackerc0w","game":"Programming","logo":null,"mature":false,"status":"Coding a Chatbot in C","partner":false,"url":"http://www.twitch.tv/hackerc0w","video_banner":null,"_id":41236491,"name":"hackerc0w","created_at":"2013-03-11T17:08:22Z","updated_at":"2015-04-01T17:17:44Z","delay":0,"followers":28,"profile_banner":null,"profile_banner_background_color":null,"views":2948,"language":"de"}}}
The way I got if the livestreamer was live was like this:
public static boolean isStreamLive(String channel) {
try {
URL url = new URL(TWITCH_STREAM.replace("$c$", channel)) );
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
String inputLine = br.readLine();
br.close();
JsonObject jsonObj = JsonObject.readFrom(inputLine);
return ( jsonObj.get("stream").isNull() )?false:true;
} catch (IOException e) {
return false;
}
}
And I mostly tried to copy the method above. But I have been checking the documentation of the library to know and I have been trying a lot of things.
The last was this:
public static String checkGame(String channel) {
if (!isStreamLive(channel)) return "El Estreamer esta Offline!";
try {
URL url = new URL( insertChannel(TWITCH_STREAM, channel) );
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
String inputLine = br.readLine();
br.close();
JsonObject object = JsonObject.readFrom(inputLine);
JsonValue value = object.get("stream").asObject();
String msg = value.valueOf("status").toString();
return msg;
} catch (IOException e) {
return "Algo raro paso :/ error: 3";
}
return channel;
}
You've got two main problems with the code you've shown.
The first problem that you're having is that you're trying to get the status out of the wrong nested object. You're getting the stream object from the original json and then trying to get the value of the status key from that, but in the json you've posted status is part of a nested channel object.
The structure of the json object is like so:
{
"_links": { ... },
"stream": {
...
"channel":{
"_links": { ... },
...
"status":"Coding a Chatbot in C",
...
}
}
}
... so you can't get status directly from stream, you need to get channel from stream and get the status from that.
The second problem is that you're trying to use valueOf() to pull a value out of a JsonObject. valueOf() is a static method which creates a new object based on the supplied input, so it doesn't actually use data in the object you call it on.
Calling value.valueOf("status") will completely ignore data in value and create a new JsonObject containing the string "status".
If you want to get the value of a nested object, you need to drill down to it with a series of successive get("objName").asObject() calls, and then call .get("key") to obtain the value you want:
// hardcoded for example, actually would be read from BufferedReader
String inputLine = "{\"_links\":{\"self\":\"https://api.twitch.tv/kraken/streams/hackerc0w\",\"channel\":\"https://api.twitch.tv/kraken/channels/hackerc0w\"},\"stream\":{\"_id\":13817896816,\"game\":\"Programming\",\"viewers\":13,\"created_at\":\"2015-04-01T13:54:54Z\",\"video_height\":1080,\"average_fps\":59.9235368156,\"_links\":{\"self\":\"https://api.twitch.tv/kraken/streams/hackerc0w\"},\"preview\":{\"small\":\"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-80x45.jpg\",\"medium\":\"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-320x180.jpg\",\"large\":\"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-640x360.jpg\",\"template\":\"http://static-cdn.jtvnw.net/previews-ttv/live_user_hackerc0w-{width}x{height}.jpg\"},\"channel\":{\"_links\":{\"self\":\"https://api.twitch.tv/kraken/channels/hackerc0w\",\"follows\":\"https://api.twitch.tv/kraken/channels/hackerc0w/follows\",\"commercial\":\"https://api.twitch.tv/kraken/channels/hackerc0w/commercial\",\"stream_key\":\"https://api.twitch.tv/kraken/channels/hackerc0w/stream_key\",\"chat\":\"https://api.twitch.tv/kraken/chat/hackerc0w\",\"features\":\"https://api.twitch.tv/kraken/channels/hackerc0w/features\",\"subscriptions\":\"https://api.twitch.tv/kraken/channels/hackerc0w/subscriptions\",\"editors\":\"https://api.twitch.tv/kraken/channels/hackerc0w/editors\",\"videos\":\"https://api.twitch.tv/kraken/channels/hackerc0w/videos\",\"teams\":\"https://api.twitch.tv/kraken/channels/hackerc0w/teams\"},\"background\":null,\"banner\":null,\"broadcaster_language\":\"en\",\"display_name\":\"hackerc0w\",\"game\":\"Programming\",\"logo\":null,\"mature\":false,\"status\":\"Coding a Chatbot in C\",\"partner\":false,\"url\":\"http://www.twitch.tv/hackerc0w\",\"video_banner\":null,\"_id\":41236491,\"name\":\"hackerc0w\",\"created_at\":\"2013-03-11T17:08:22Z\",\"updated_at\":\"2015-04-01T17:17:44Z\",\"delay\":0,\"followers\":28,\"profile_banner\":null,\"profile_banner_background_color\":null,\"views\":2948,\"language\":\"de\"}}}";
JsonObject object = JsonObject.readFrom(inputLine); // parse json into object
JsonObject stream = object.get("stream").asObject(); // get "stream" sub-object
JsonObject channel = stream.get("channel").asObject(); // get "channel" sub-object
JsonValue status = channel.get("status"); // get the value of "status"
String msg = status.asString();
System.out.println(msg); // Coding a Chatbot in C
I'm working on an android app, and the app must save a java object in json format into the SQLite database. I wrote the code for this operation, then they must extract the Json object and reconvert it into a Java Object.
When I try to call the method for deserializing the json object in to a string, I found this error in Android Studio:unhandled exception org.json.jsonexception
When I try to catch JSONException e the program runs but don't deserialize the json object.
This is the code for the method:
private void read() throws JSONException {
SQLiteDatabase db = mMioDbHelper.getWritableDatabase();
String[] columns = {"StringaAll"};
Cursor c = db.query("Alle", columns, null, null, null, null,null );
while(c.moveToNext()) {
String stringaRis = c.getString(0);
JSONObject jObj = new JSONObject(stringaRis);
String sPassoMed = jObj.getString("passoMed");
final TextView tView = (TextView) this.findViewById(R.id.mainProvaQuery);
tView.setText(sPassoMed);
// }
}
}
Can you help me please?
Yes, you need to catch the exception.
But when you catch it, you should not just throw it on the floor. Your application needs to do something about the exception. Or if you / it is not expecting an exception to occur at runtime, then at least you should report it. Here's a minimal example (for an Android app)
try {
...
JSONObject jObj = new JSONObject(stringaRis);
...
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
Of course, this does not solve your problem. The next thing you need to do is to figure out why you are getting the exception. Start by reading the exception message that you have logged to logcat.
Re this exception message:
org.json.JSONException: Value A of type java.lang.String cannot be converted to JSONObject
I assume it is thrown by this line:
JSONObject jObj = new JSONObject(stringaRis);
I think that it is telling you is that stringaRis has the value "A" ... and that cannot be parsed as a JSON object. It isn't JSON at all.