Do proper parsing of the JSON as , you see yours response:-
{ "Details":[{"Status":"NO UPDATES"}]}
So Firstly try to make the object of the JSONObject than after the JSONArray , look at below example:-
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray detailsArray = jsonObject.getJSONArray("Details");
String status = dataArray.getJSONObject(0).getString("status");
Toast.makeText(getBaseContext(), "Please wait...",100+status).show();
Answer from Ravindra Kushwaha on Stack OverflowDo proper parsing of the JSON as , you see yours response:-
{ "Details":[{"Status":"NO UPDATES"}]}
So Firstly try to make the object of the JSONObject than after the JSONArray , look at below example:-
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray detailsArray = jsonObject.getJSONArray("Details");
String status = dataArray.getJSONObject(0).getString("status");
Toast.makeText(getBaseContext(), "Please wait...",100+status).show();
your code should be like this
JSONObject object = new JSONObject(jsonResult);
JSONOArray details = object.getJSONArray("Details");
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String status = c.getString("Status");
}
Toast.makeText(getBaseContext(), "Please wait...",100).show();
First problem
You're passing the wrong value into the JSONObject constructor. Look at this piece of code:
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
System.out.println(inputLine);
}
JSONObject obj = new JSONObject(inputLine);
The while loop is only going to complete when inputLine is null - so your final line is equivalent to:
JSONObject obj = new JSONObject(null);
... which obviously isn't what you want. I think you want:
JSONObject obj = new JSONObject(response.toString());
Note that you probably want to use StringBuilder rather than StringBuffer as well, to avoid pointless synchronization.
Next problem
If your JSON is actually of the form [ ... ] then it's an array, not an object at the top level. So you probably want:
JSONArray arr = new JSONArray(response.toString());
for (int i = 0; i < arr.length(); i++)
{
String drzava = arr.getJSONObject(i).getString("Država");
System.out.println(drzava);
}
After all, if you look at your JSON, it doesn't have Država as the name of a property with an array as the value.
I think you are using wrong input for your JSonObject:
double responseCode = conn.getResponseCode();
try (InputStreamReader sr =new InputStreamReader(conn.getInputStream());
BufferedReader in = new BufferedReader(sr)){
// ^ this is Jdk7+, will close your streams after the block exists, like in finally block
...
JSONObject obj = new JSONObject(response.toString()); // pass the input as a String
....
}catch (IOException | JSONException e) {
e.printStackTrace();
}
Your response variable holds the input in a form of a String, whereas inputLine holds only single line. And after the last iteration, it's set to null. Which will cause an NPE.
Key to the answer : Gson or not, parsing the json string is the key to the answer.
From the comments by Siddharth below.
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonResults.toString()).getAsJsonObject() ;
JsonArray results = json.getAsJsonArray("results");
JsonObject result = results.get(0).getAsJsonObject();
customerAddress = result.get("formatted_address").getAsString();
Alternative :
I failed to read the edit 3 part of the question and failed to look at the gson tag. So i ended up providing the below alternative.
JSONObject jsono = new JSONObject (myjsonstring);
JSONArray myListsAll= new JSONArray(jsono.getString("results"));
for(int i=0;i<myListsAll.length();i++){
JSONObject jsonObject1 = (JSONObject) myListsAll.get(i);
JSONArray myarray= new JSONArray(jsonObject1.getString("address_components"));
for(int i1=0;i1<myarray.length();i1++)
{
JSONObject jsonobject2 = myarray.getJSONObject(i1);
System.out.println(""+jsonobject2.getString("long_name"));
System.out.println(""+jsonobject2.getString("short_name"));
System.out.println(""+jsonobject2.getString("types"));
}
}
Output
Towards Wadgao Sheri
Towards Wadgao Sheri
["route"]
Sainikwadi
Sainikwadi
["neighborhood","political"]
Wadgaon Sheri
Wadgaon Sheri
["sublocality","political"]
Pune
Pune
["locality","political"]
Pune
Pune
["administrative_area_level_2","political"]
Maharashtra
MH
["administrative_area_level_1","political"]
India
IN
["country","political"]
411014
411014
["postal_code"]
Sainikwadi
Sainikwadi
["neighborhood","political"]
Wadgaon Sheri
Wadgaon Sheri
["sublocality","political"]
Pune
Pune
["locality","political"]
Pune
Pune
["administrative_area_level_2","political"]
Maharashtra
MH
["administrative_area_level_1","political"]
India
IN
["country","political"]
411014
411014
["postal_code"]
Wadgaon Sheri
Wadgaon Sheri
["sublocality","political"]
Pune
Pune
["locality","political"]
Pune
Pune
["administrative_area_level_2","political"]
Maharashtra
MH
["administrative_area_level_1","political"]
India
IN
["country","political"]
411014
411014
["postal_code"]
Pune
Pune
["administrative_area_level_2","political"]
Maharashtra
MH
["administrative_area_level_1","political"]
India
IN
["country","political"]
Pune
Pune
["locality","political"]
Pune
Pune
["administrative_area_level_2","political"]
Maharashtra
MH
["administrative_area_level_1","political"]
India
IN
["country","political"]
Pune
Pune
["administrative_area_level_2","political"]
Maharashtra
MH
["administrative_area_level_1","political"]
India
IN
["country","political"]
Maharashtra
MH
["administrative_area_level_1","political"]
India
IN
["country","political"]
India
IN
["country","political"]
You start off with ...
JsonObject response = new JsonObject().getAsJsonObject(jsonResults.toString());
This makes no sense. You've created a new, empty JsonObject then attempt to retrieve an element from it using your entire JSON string as the property name. Therefore, yes ... response is null.
Your JSON is an object. It contains two fields; results which is an array of objects and status which is a String.
Normally when using Gson you'd create matching Java classes and use a Gson instance to deserialize to them. If you don't want to do that, then you'd Gson's JsonParser to parse the Json and then access it through the various Json* classes:
/// jsonResuts is a String containing the JSON you list.
JsonObject obj = new JsonParser().parse(jsonResults).getAsJsonObject();
JsonArray resultsArray = obj.getAsJsonArray("results");
Now you have the array of objects and can delve deeper into that using the same methods/classes from Gson I used above.
for (JsonElement e : resultsArray) {
JsonObject resultsObj = e.getAsJsonObject();
JsonElement formattedAddress = resultsObject.get("formatted_address");
String addressAsString = formattedAddress.getAsString();
System.out.println(addressAsString);
// The above can be chained and reduced to one line:
// System.out.println(e.getAsJsonObject().get("formatted_address").getAsString());
}
There's a couple of things you could do better here. But your main problem is that you are doing async tasks(backgroundtask) and not handling a proper callback.
What happens in the following:
- Starting of the async task.
- You sleep for 3 seconds (Which is probably to try to make the async finish before the code continues.)
- The Async task might not have finish have finished in the 3 seconds.
- Your try to parse the JSON that has not been received yet.
- This throws a nullpointer.
Now while crashing the async task still runs and finishes. I'm not sure if you save this JSON and then it becomes readable while completing and becomes available the second time, or that the second time the task might finish within 3 seconds.
What you should do
- Starting of the async task.
- Do Not let the thread sleep.
- In the async task
onPostExecutehave a callback to your main thread. - Have the callback return the JSON obtained from the task.
- Now parse the JSON you will have, if the call itself did succeed.
To achieve this look here https://developer.android.com/training/best-background.html
It should provide enough information to get this piece of code stable.
Another way you can place intent inside your post execute.
in your Activity's onCreate method
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new RetrieveGamesBGTask(Splash.this).execute();
}
now in your RetrieveGamesBGTask's onPostExecute method
@Override
protected void onPostExecute(String result) {
Log.d("haha", "hehe");
json_result = result;
Intent intent = new Intent(context, Games.class);
intent.putExtra("json_data", json_string);
intent.putExtra("json_data",json_result);
context.startActivity(intent);
}
Sometimes this problem occurs when accidentally using a primitive type as return type of the getter of a non-primitive field:
public class Item
{
private Float value;
public float getValue()
{
return value;
}
public void setValue(Float value)
{
this.value = value;
}
}
Notice the "float" instead of "Float" for the getValue()-method, this can lead to a Null Pointer Exception, even when you have added
objectMapper.setSerializationInclusion(Include.NON_NULL);
If you don't want to serialize null values, you can use the following setting (during serialization):
objectMapper.setSerializationInclusion(Include.NON_NULL);
Hope this solves your problem.
But the NullPointerException you get during deserialization seems suspicious to me (Jackson should ideally be able to handle null values in the serialized output). Could you post the code corresponding to the PersonResponse class?
You are right, Double can handle null value, and double can't.
In my case, my property was of type Long but the getter was returning a long value and not a Long value. This was acceptable as far as the value was not null. But when the value was null, jackson was not able to serialize the null value for long.
Just changing the getter to return a Long instead of a long fixed it.
Verify if your getter return a Double and not a double in your case.
ps: I know this question is quite old but since I was having the same problem and the question was 2nd in Google answers... Seemed fair to answer it later than never
I don't know if this is still valid but, I solved this problem by changing the version of com.fasterxml.jackson.dataformat:jackson-dataformat-yaml. Earlier I was using 2.3.0 and was getting this same error. I changed it to 2.7.8 and it is working fine now.
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);
}
By obj.get("name"), you try getting value by key name from a top-level of your json request, while it's a property of a second-level object
In pseudo-code (skipping casting and null-checks) it should look like this:
obj.get("products")[0].get("name")
In Service.java you print obj inside for loop. Your print says that key is products and value is an array of objects.
So in following line obj is that top-level object and not contains “name” field.
String name = (String) obj.get("name");
System.out.println("name: " +name);
What if you call obj.get(“products”) and try to cast it into a collection? Then trying to fetch the first index from the collection. It should contain the inner object which contains name key and value.
If you want to have your email String contain the value "null", then you should use the String.valueOf() method instead of the .toString() method. The difference is that String.valueOf() will return the String "null", where .toString() will throw a NullPointerException, instead.
So your line could look like this:
String email = String.valueOf(validatableResponse.extract().jsonPath().get("email[0]"));
This post explains it well.
What value should be returned, if your value is null?
At first I´d set the String to the value, wich should be returned when the result is null. Then I´d try to set the new value. If this fails, the method will return the value that was set first. Try and catch is used to avoid a crash when the NullPointer is thrown.
public String recipientEmail() {
String email="";
try{
email = validatableResponse.extract().jsonPath().get("email[0]").toString();
}catch(NullPointerException ex){
ex.printStacktrace();
}
return email;
}
The NPE comes from Toast initialization. Make sure the context you pass there is not null.
Since you use the toasts in exception catch blocks, log the exception stacktraces with e.g. e.printStackTrace() to get a hold on the root cause. (Prime suspect: NetworkOnMainThreadException)
For NetworkOnMainThreadException, do your network ops on a background thread. See How to fix android.os.NetworkOnMainThreadException? for more.
In your call to Toast, the context variable is most likely null.
Never catch a NullPointerException. Make sure it never gets thrown.
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();
Instead of your
convertStreamToString()method try using system providedEntityUtils.toString(entity).IMPORTANT: do not catch generic
Exception, this hides unchecked (runtime) exceptions. You might be hiding theJSONExceptionthat happens in JSONObject constructor.
Update:
You are calling SendHttpPost and not assigning result to variable:
HandleJSON.SendHttpPost(URL, jsonobj);
should be:
regName = HandleJSON.SendHttpPost(URL, jsonobj);
I don't see anything wrong with this, could you tell me what is the use of regname ?
at your mainactivity just change the following:
regname = HandleJSON.SendHttpPost(URL, jsonobj);
Your not calling back regname to be assigned to name and sessionid that you are returning at the sendhttppost.
solved:
Some of the events field values were NULL in DB and this was the Cause.
In ret.put("events", eventArrayList);
eventArrayList refers ArrayList<ArrayList> and few field values in <ArrayList> were NULL,
From above Ex: (Look into the Null value in inner arraylist which is at second index)
{events=[[98, EvebtTitle, Mon Dec 03 2012 10:45:00 +0530, Wed Oct 17 2012 11:15:00 +0530, 0, 0, 0, 0, 1, NJ, ], [118, testDec, Wed Dec 05 2012 09:00:00 +0530, Wed Dec 05 2012 10:00:00 +0530, 0, 0, 0, null, 1, null, ]]}
After removing the Null values from the inner ArrayList things are working fine.
One thing that comes to my mind about method
public String toJson(Object src)
is GSON documentation which states "This method should be used when the specified object is not a generic type. If the object is of generic type, use toJson(Object, Type) instead."
Another thing is that the null pointer exception may be caused by any other object, not specifically the HashMap. It seems that you took it for granted, but I recommend debugging your code.