How to catch JSON null result on Android? - android

I have an Android Application that invoke a REST webservice and get the JSON answer.
When I enter a wrong parameter I can catch the error without problem but sometimes some results on the JSON are null. How can I catch that situation?
My Android code:
try {
JSONObject jsonObj = new JSONObject(results);
JSONArray result = jsonObj.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String string04 = c.getString("string04");
String string05 = c.getString("string05");
TextView txt1 = (TextView)findViewById(R.id.textView1);
txt1.setText(string04);
TextView txt2 = (TextView)findViewById(R.id.textView2);
txt2.setText(string05);
JSONArray dest = c.getJSONArray("dest");
for (int o = 0; o < dest.length(); o++) {
JSONObject d = dest.getJSONObject(o);
JSONArray pred = d.getJSONArray("pred");
for (int u = 0; u < pred.length(); u++) {
JSONObject e = pred.getJSONObject(u);
String string13 = e.getString("string13");
TextView txt4 = (TextView)findViewById(R.id.textView4);
txt4.setText(string13);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("error", e.getMessage());
}
A good JSON result would be like this:
{
"result": [{
"string01": "104",
"string02": "104 - blablabla",
"string03": "104",
"string04": "blobloblo",
"string05": "blablabla",
"dest": [{
"pred": [{
"time": 1461348846,
"sec": 102,
"min": 1,
"string11": "514-String",
"string12": "Some String",
"string13": "Some other String",
"number": 0
}]
}]
}]
}
But sometimes, when there is no data to show, I get something like this:
{
"result": [{
"string01": "104",
"string02": "104 - blablabla",
"string03": "104",
"string04": "blobloblo",
"string05": "blablabla",
"dest": [{"pred":[]}]
}]
}

The JSON parser has "opt" methods which will return NULL if there's no object for the matching condition. These methods are there similar to get methods.
E.g: getJSONObject("column") will throw an exception if there isn't a value for "column"
optJSONObject("column") will simply return a NULL value if it doesn't exist. I personally find the "opt" methods handy when working with JSONs whose values might be missing at runtime.

Related

Not able to extract array elements from JSON in android

I have been trying to extract array elements from my JSON, but unable to, so far.
I have the following JSON:
{
"Sample JSON": [{
"Title": "Title1",
"Audit": [{
"auditId": "01",
"type": "sampleType",
"auditText": "sampleText",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "02",
"type": "sampleType2",
"auditText": "sampleText2",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
},
{
"Title": "Title2",
"Audit": [{
"auditId": "03",
"type": "sampleType3",
"auditText": "sampleText3",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "04",
"type": "sampleType4",
"auditText": "sampleText4",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
}
]
}
I want to extract the array elements of the array 'answer'.
I get exception in the line indicated in comment in the method below:
public void getAudit(String myJSON) {
auditList = new ArrayList<AuditList>();
String title;
String auditId;
String type;
String auditText;
ArrayList<String> answer = new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONArray jssArray = jsonObj.getJSONArray("Sample JSON");
int jsonArrLength = jssArray.length();
for (int i = 0; i < jsonArrLength; i++) {
JSONObject jsonChildObj = jssArray.getJSONObject(i);
title = jsonChildObj.getString("Title");
JSONArray jssArray1 = jsonChildObj.getJSONArray("Audit");
for (int i1 = 0; i1 < jssArray1.length(); i1++) {
JSONObject jsonChildObj1 = jssArray1.getJSONObject(i1);
type = jsonChildObj1.optString("type");
auditText = jsonChildObj1.optString("auditText");
auditId = jsonChildObj1.optString("auditId");
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
//Getting exception in above line
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
AuditList aList = new AuditList();
aList.setQuesId(auditId);
aList.setQuesText(auditText);
aList.setQuesTypw(auditType);
aList.setAnswer(answer);
aList.setCategoryName(title);
auditList.add(aList);
}
}
.
.
.
.
.
}
I found the exception occurring in the line indicated above using the debugger.
Couldn't find a way to extract array elements of the array 'answer'.
Please help.
if(!jsonChildObj1.get("answer").toString().equals("")){
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
}
The exception that occurred to you because of Empty Data (""). To Prevent this validate it and getJSONArray(). refer
The way I do this kind of stuff is by going to this link and then paste my json there and get my class. After that, you can go and add Gson to your gradle by adding this line to your build.gradle:
compile 'com.google.code.gson:gson:2.6.2'
Then just create an instance of the created class that you just created and convert json into your target class:
NewClass classObject = new Gson().fromJson(YOUR_JSON, NewClass.class);

Remove The Json Value From Json

I want to remove json value from below json file .
This is my json object :
{
"Approximation": {
"name": "Approximation",
"description": [
"Approximation",
"Approximation",
"Approximation"
],
"video": [
"evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd",
"evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd",
"evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"
]
}
}
and this is what I'm trying
Code :
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
jsonArr.remove(i);
children = new ArrayList<ChildrenEvent>();
et = new Events(jsonObj.optString("name"));
ct = new ChildrenEvent(jsonObj.optString("description"));
langs.add(et);
children.add(ct);
}
I am not sure what you are trying to achieve here. You don't need to remove the key "Approximation" to get the data.
This is how you parse this JSON.
{
"Approximation": {
"name": "Approximation",
"description": ["Approximation", "Approximation", "Approximation"],
"video": ["evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd", "evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd", "evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"]
}
}
Code,
JSONObject mainObj = new JSONObject(json_string);
JSONObject appproxObj = mainObj.getJSONObject("Approximation");
// Parse name
String name = appproxObj.getString("name");
et = new Events(name);
langs.add(et);
// Parse descriptions
JSONArray descriptions = appproxObj.getJSONArray("description");
children = new ArrayList<ChildrenEvent>();
for (int i = 0; i < descriptions.length(); i++ ) {
String description = descriptions.getString(i);
ct = new ChildrenEvent(description);
children.add(ct);
}
Still if you need the JSON without key "Approximation", the variable appproxObj has the JSON without the key.
There is a method in JsonObject, that is remove(). It will help you to remove any key from jsonObject;
Use this:-
jsonObject.remove("key");

how to parse this JSONArray

Hi guys i have this JSONObject I'm having hard time to parse it.
Here's the JSON,
{
"query": {
"count": 2,
"created": "2016-11-07T15:29:47Z",
"lang": "en-US",
"results": {
"rate": [{
"id": "USDINR",
"Name": "USD/INR",
"Rate": "66.7700",
"Date": "11/7/2016",
"Time": "3:27pm",
"Ask": "66.8000",
"Bid": "66.7700"
}, {
"id": "USDEUR",
"Name": "USD/EUR",
"Rate": "0.9060",
"Date": "11/7/2016",
"Time": "3:29pm",
"Ask": "0.9065",
"Bid": "0.9060"
}]
}
}
}
As you can see above there are two "Rate" I want to store first "Rate" to a String array called Result[0] and second "Rate" to Result[1].
Here what I'm trying.
JSONObject object = new JSONObject(JSON);
JSONObject rateObject = object.getJSONObject("rate");
JSONArray rateArray = rateObject.getJSONArray("Rate");
result[0] = rateArray.getString(0);
result[1] = rateArray.getString(1);
I know maybe I'm doing this like stupid. So please help me out.
To Get the array I would try this:
JSONObject object = new JSONObject(JSON);
JSONObject rateObject = object.getJSONObject("results");
JSONArray rateArray = rateObject.getJSONArray("rate");
And then use a for to read all objects in the array:
int length = rateArray.length();
for (int i =0; i < length; i++){
JSONObject rate = rateArray.getJSONObject(i);
String rateResult = rate.getString("Rate");
}
Your formatted JSON looks like this
{
"query":{
"count":2,
"created":"2016-11-07T15:29:47Z",
"lang":"en-US",
"results":{
"rate":[
{
"id":"USDINR",
"Name":"USD/INR",
"Rate":"66.7700",
"Date":"11/7/2016",
"Time":"3:27pm",
"Ask":"66.8000",
"Bid":"66.7700"
},
{
"id":"USDEUR",
"Name":"USD/EUR",
"Rate":"0.9060",
"Date":"11/7/2016",
"Time":"3:29pm",
"Ask":"0.9065",
"Bid":"0.9060"
}
]
}
}
}
To get the rate array you have to this
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray rateArray = jsonObject.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
Then query rate array like this
JSONObject rateJSON = (JSONObject)rateArray.get(index);
String id = rateJSON.getString("id"); //Or any other field of rate
Anthony,
You need to go from the root element ( query ) to the "rate" node :
JSONArray rates = object.getJSONObject("query").getJSONObject("results").getJSONArray("rate")
result[0] = rates.getJSONObject(0).get("Rate")
result[1] = rates.getJSONObject(1).get("Rate")
you need to do this
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject queryObj = jsonObj.getJSONObject("query");
JSONObject resultObj = queryObj.getJSONObject("results");
JSONArray rateArr = resultObj.getJSONArray("rate");
result[0] = rateArr.getJSONObject(0).getString("Rate");
result[1] = rateArr.getJSONObject(1).getString("Rate");
Try this:
JSONArray rateArray = new JSONObject(JSON)
.getJSONObject("query")
.getJSONObject("results")
.getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");

is my JSON response correct? and why i see this exception when i try to retrieve it?

my problem is that i have an asp. web service .. and it gives me the following result when i invoke it :
[
{
"_OrderDetails": [
{
"ProductName": "FUCHS SUPER GT SAE 10W30 6X5 / FP10100010102",
"TotalAfterDiscount_Lc": "7500",
"MeasureUnitName": "كرتونة",
"TotalPrice_Lc": "7500",
"PricePerUnit_Lc": "75",
"Quantity": "100"
}
],
"Id": "274",
"OrderDate": "4/10/2014 12:00:00 AM",
"Number": "16",
"CustomerName": "الأسد",
"Note": ""
}
]
and in the main activity i do the following :
Gson gson = new Gson();
Log.e("Response", responseJSON);
if (responseJSON != null) {
try {
JSONObject jsonObj = new JSONObject(responseJSON);
//JSONArray jsonarr =new JSONArray();
// details=jsonObj.getJSONObject(0);
// Getting JSON Array node
details = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String product = c.getString(TAG_PRODUCT);
Log.e("prodeuct",product+"");
}
i see the response in the logcat correctly but when i try to get any object from the array i see a JSON exception it says :
JSON array can't be converted to JSON object !!!
please can anyone help me??
Because your json return jsonarray and you are try to access jsonobject.
Change your code:
if (responseJSON != null) {
try {
JSONArray jsonObj = new JSONArray(responseJSON);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
// your code
}
Chang to JSONArray
if (responseJSON != null) {
try {
JSONArray array = new JSONArray(responseJSON)
}
http://jsonviewer.stack.hu/ use it to view your json and resolve it accordingly. you are using json array as json object.
use these:
JSONObject jsonObj = new JSONObject(responseJSON);
to
JSONArray jr = new JSONArray(responseJSON);

get the index with value using arrayobject and store in array list [duplicate]

This question already has answers here:
get the array index with value using arrayobject and store in array list
(2 answers)
Closed 10 years ago.
[ {
"question_id": 13,
"creation_date": 10,
"name": " certain degrees",
"tags": [
"android",
"sensor"
],
.....
...}
]
Here is the api I want to get the tags array ,the tag array contains only index and value,i want to get the array using array object and finally store in array list, i have tried but fail to get the error has been occured.
02-20 15:45:37.323: I/System.out(1165): org.json.JSONException: Value android at 0 of type java.lang.String cannot be converted to JSONObject
could anybody help me to solve this problem.
tagarray = questionobj.getJSONArray("tags");
for(int j=0;j<tagarray.length();j++){
//tagobject = tagarray.getJSONObject(j);//..if i comment this line the full array list is displaying but i need for each question allocated tags to display..am i clear..
//if(tagobject!=null){
tagname.add(tagarray.getString(j));
///tagname.add(0, null);
//}
}
your json format is not correct
try like that;
{"question":
{"question_id": "13",
"name": "certain degrees",
"tags": [{"android":"N", "sensor":"Y"}]
}}
You can use http://jsonviewer.stack.hu/, to be sure correction of your json data
I sugest you try this code,
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String text = "[ { \"question_id\": 13, \"creation_date\": 10, \"name\": \"certain degrees\", \"tags\": [ \"android\", \"sensor\" ] } ]";
System.out.println(text);
JSONArray jsonArray = new JSONArray(text);
JSONObject jsonObjetc = jsonArray.getJSONObject(0);
JSONArray tagarray = jsonObjetc.getJSONArray("tags");
System.out.println(tagarray);
for(int j=0;j<tagarray.length();j++){
System.out.println(tagarray.getString(j));
}
}
}
Good luck, Aron
Try this,
ArrayList<String> list = new ArrayList<String>();
String text = "[ { \"question_id\": 13, \"creation_date\": 10, \"name\": \"certain degrees\", \"tags\": [ \"android\", \"sensor\" ] } ]";
try {
JSONArray jarray = new JSONArray(text);
for (int i = 0; i < jarray.length(); i++) {
JSONArray j_array = jarray.getJSONObject(i)
.getJSONArray("tags");
for (int j = 0; j < j_array.length(); j++) {
String str = j_array.getString(j);
list.add(str);
}
}
} catch (Exception e) {
}
Try This
tagarray = questionobj.getJSONArray("tags");
for(int j=0;j<tagarray.length();j++)
{
tagname.add(tagarray.getJSONObject(j).getString("android"));
}

Categories

Resources