I am working on json parser. In json response some values contains boolean or null values, then how to check whether it is boolean or null? For example : user = false or user = null . At the time of parsing it gives exception as "user is not jsonobject".
JSONObject json = new JSONObject(query);
JSONObject info = json.getJSONObject("info");
JSONObject user = info.getJSONObject("user");
Thanks,
Vishakha.
Have you tried ingo.optBoolean("user")?
From the SDK documentation for optBoolean:
Returns the value mapped by name if it exists and is a boolean or can be coerced to a boolean. Returns false otherwise.
Note that null will be treated as a false value in this example.
isNull() you can use if(json.isNull("user")||your conditions)
I think the problem might be that you are trying to get a JSONArray with getJSONObject(). try json.getJSONArray("info"). I had the same problem that i was trying to do if(object.getJSONObject("string") == null) but it threw an exception when trying to get the object to check for its value, and .optBoolean worked perfectly
JSONObject json = new JSONObject(data);
String user = json.getString("user");
variable.setUser(courses_icon_file_name == null ? "": user);
Related
Hitting a brick wall in my code at the moment for fetching json objects from multiple pages(using a loop) in a AsyncTask. It reaches the last page, but getting the correct if statement to ensure that the loop DOESN'T run again and continues on is baffling me.
String data = //some correct json data with next element that holds a uri parseable string
JSONObject initial = new JSONObject(data);
String next = initial.getString(nextObjSTR);
//gonna start from the "last" page and recursively return to the 1st page
if(*The if condition I need help with*) {
//there is another page
makeConnection(Uri.parse(next));
}
Basically, the last page of json elements has a next element with a null or no element value, which triggers the IOException error caught in makeConnection method because my initial if statement has always been failing.
Can I get a reason or help as to the appropriate if check for Strings from json? I've tried String != null as NullPointerExceptions occur if I use any method from String to compare. Likewise, JsonObject.NULL comparison doesn't work for me either.
None of the other answers worked, and I ended up questioning whether the element was really null despite looking at the parsed json data via an online tool. In the end, JSONObject.IsNull(element mapping name) is the right approach.
If you're sure that the value is either null (empty) or a correct URI, and assuming that the nextObjSTR key is always present in the data JSON, then that will do:
if (next != null && !next.trim().isEmpty()) {
makeConnection(Uri.parse(next));
}
Or, since you're on Android, it's better use the more convenient method:
if (!TextUtils.isEmpty(next)) {
makeConnection(Uri.parse(next));
}
You can use the optString Method of the JSONObject. If the JSON key is not this method will return a empty string, so you can check it easily:
String next = initial.optString(nextObjSTR);
if ( ! next.isEmpty() ) {
makeConnection(Uri.parse(next));
}
Source: https://developer.android.com/reference/org/json/JSONObject.html#optString(java.lang.String)
you must check value with key is has in json object.
Try below code:
JSONObject initial = new JSONObject(data);
if(initial.has(nextObjSTR)) {
String next = initial.getString(nextObjSTR);
if (next != null && !next.isEmpty()) {
makeConnection(Uri.parse(next));
}
}
I do like this...
String value;
if(jsonObject.get("name").toString.equals("null")){
value = "";
else{
value = jsonObject.getString("name");
}
Working on a project where i am performing some operation based on instruction code. there are some json keys. where i am getting all the required values but have problem to get one among all. I am a initial level developer here.
Note : at everytime when i try to get instruction value in my android code i get 0.can anybody suggest me how should i go through now.
You can refer screenshot for my code.
From server I am getting proper json response.
{
"success": "true",
"error": "",
"result": [
{
"message": "Network is requesting permission to connect to your phone",
"instruction": 111,
"imei_no": "b2b5e4012e3c8b49",
"socket_user_id": "u566135811c9a2"
}
]
}
You are accessing the JSON value with not the correct key.
The correct way to get the key value is:
int instruction= json.getJSONArray("Result").getJSONObject(0).optInt("instruction")
Global version:
json.getJSONArray("Result").getJSONObject(index_of_array).optInt("instruction")
public long optLong (String name)
Returns the value mapped by name if it exists and is a long or can be coerced to a long, or 0 otherwise. Note that JSON represents numbers as doubles, so this is lossy; use strings to transfer numbers via JSON.
http://developer.android.com/reference/org/json/JSONObject.html#optJSONArray(java.lang.String)
Try this Hope this will Work!
final JSONObject obj = new JSONObject(response.toString());
final JSONArray array= obj.getJSONArray("result");
final int n = array.length();
for (int i = 0; i < n; ++i) {
final JSONObject result= array.getJSONObject(i);
System.out.println(result.getString("message"));
System.out.println(result.getString("instruction"));
}
It looks like you're not retrieving "result" from json. You'll need to retrieve result, which should give you an array, and then retrieve the first object of the array, in order to retrieve its property instruction.
Its a result of optInt method:
public int optInt(java.lang.String key)
Get an optional int value associated with a key, or zero if there is no such key
or if the value is not a number. If the value is a string, an >attempt will be made to evaluate it as a number.
You should get JsonArray "Result" and next get first JsonObject. Now, you can access to "instruction".
Example JSON Page
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.155455,-0.165058&sensor=true
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
// This works and returns address
JSONArray resultArry = reader.getJSONArray("results");
String Address = resultArry.getJSONObject(1).getString("formatted_address").toString();
Log.e("Address", Address);
// Trying to get PostCode on code below - this is not working (log says no value at address components)
JSONArray postCodeArray = reader.getJSONArray("address_components");
String postCode = postCodeArray.getJSONObject(1).getString("long_name").toString();
Log.e("PostCode", postCode );
This code returns the address correctly. How can I get the post code long_name which is inside address_components?
Solution
I had to get each array, and then get the post code value.
I am using the value 7, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
reader.getJSONObject(1).getJSONArray("address_components");
Your problem is that results is a JSONArray that contains a child JSONObject composed of several children: "address_components", "formatted_address", "geometry", and "types". The result array actually contains many of these such objects, but let's focus on just the first child for now.
Look carefully at your code. With this line:
JSONArray resultArry = reader.getJSONArray("results");
You are getting the entire results. Later on, you then call the same method again:
JSONArray postCodeArray = reader.getJSONArray("address_components");
But you're asking for an "address_components" from the reader, where I do not expect you'll find anything (having already read the entire result before.) You should instead be working with the JSONArray you already got before, since it already contains the entire result.
Try something like:
JSONObject addressComponents = resultArry.getJSONObject(1).getJSONObject("address_components");
String postCode = addressComponents.getString("long_name");
Note: I don't know why you're singling out JSONObject #1 (as opposed to 0, which is the first, or any other one of them) and I also am not sure why you named the String postCode. So if I've misunderstood your intention, I apologize.
Is difficult to find the error... because all looks well. The problem maybe can exist when you make the json.put("address_components", something);
So my advice is put a breakpoint at this line
JSONArray postCodeArray = reader.getJSONArray("address_components");
o display the json in logcat
Log.d("Simple", reader.toString());
Then Paste your json in this web page to view more pretty
http://jsonviewer.stack.hu/
and check if all keys are stored well.
Solution
Need to get each array, and then get the post code value. The value 7 is used, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
My JSON stream can be different each time. For example sometime it can include a "Song" field and sometime not.
I am getting this fields value asText ? How to tell Jackson to get this value as an Empty String if it is not defined ?
Example
"Content": "MusicContent",
"Song": "Track_1",
if try node.get("Song").asText() it will give "Track_1"
"Content": "MusicContent",
Now , if i try to get node.get("Song") it gives null pointer exception. I want to get an empty string when calling asText().
How can i do that ?
Thanks
You could check for null before calling the asText() on the node. i would probably do it like this :
if (node.get("Song") != null){
myString = node.get("Song").asText();
} else {
myString = "";
}
Or in a fancy way like this :
myString = ((node.get("Song")!=null) ? node.get("Song").asText() : "");
I have this JSON string that I am recieving after I make a purchase from the playstore and I am apparently missing something in my code when I am trying to parse it.
PurchaseInfo:{"orderId":"12999763165555505758.1317333586444405",
"packageName":"com.mypkgname.myapp",
"productId":"monthly_purchase_01",
"purchaseTime":1357456489000,
"purchaseState":0,
"purchaseToken":"yrynypfkdncvhlxdbypysvwz.AO-J1OxFkndfqkClAqbbYAOApkMgTG4VX9Ef0uNP0FIs9-xGrXivkbx3FNMA2yNU12K_sbvRGFcknVBTfisI-uZawCXLGlMX4v4Zw8GFOmS0Q6PIbiITTGqn5h1QbEB4Rv84sXdUJHP3B_UQfujZN7ADi9bm_N4_iA"}
Here is the snippet of code I am using it to attempt the parsing
try {
JSONObject j1 = new JSONObject(tester1);
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
int count = mPurchInfo.length();
final String[] purchInfo = new String[count];
JSONObject q1 = mPurchInfo.getJSONObject(0);
purchInfo[0] = q1.getString("orderId");
purchInfo[1] = q1.getString("packageName");
purchInfo[2] = q1.getString("productId");
purchInfo[3] = q1.getString("purchaseTime");
purchInfo[4] = q1.getString("purchaseState");
purchInfo[5] = q1.getString("purchaseToken");
orderID=purchInfo[0];
} catch (JSONException e) {
Log.e("Error","Yes");
}
I am catching the an error as I see this last log statement in my log but I am still trying to learn the parsing JSON Strings
I hope I am at least close
Ideally I would like to have Strings set to all the values in the JSON String
orderID = ??
packageName = ??
etc.
Thanks
I have this JSON string that I am recieving after I make a purchase from the playstore
If that's really what you get back, you need to contact them and tell them to fix their API; that string is not valid JSON. There are two problems with it:
A JSON document must have an object or array as the top-level item. The string as quoted is missing a { at the beginning and a } at the end.
All keys in JSON must be in double quotes. The first one, PurchaseInfo, is not.
Also, your code is doing this:
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
...but if it were valid JSON, PurchaseInfo wouldn't be an array, it'd be an object.
Looking at it, if you remove the PurchaseInfo: at the beginning, it's valid. Once you've removed that, this line:
JSONObject j1 = new JSONObject(tester1);
...will give you an object from which you can query information:
String orderId = j1.getString("orderId");