how check is the json Array available and exist? - android

I'm loading a json array in my app.but i need to know if the json array is exist or not? because if the json array isn't exist, the app will crash.
for example, I have this json:
{
"music1":
[
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
},
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
},
]
}
and I want to know is there any json object named "music1" in my code or not, and then if there was I want to get the json array and show it in a list in my android app.
I'm looking forward a hero that could help me!

I wish this explanation would fit in a comment.
Anyway:
{
"music1":
[
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
},
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
}
]
}
Let call the above json object o.
So to check if o has music1, all you need to check is write the following line:
if(o.has("music1")){
JSONArray array= o.getJSONArray("music1");
}
Then you extract the objects of the json array :
for(int i=0;i<array.length();i++){
array.getJSONObject(i);
}

Check the availability of field:
if(jsonObj.has("music1")){
//yes
}
or this case:
JSONArray mJSONArray = jsonObj.optJSONArray("nmusic1");
If array is not available mJSONArray will be null

Related

How to fetch multilevel JSON using volley?

My JSON Example where i am willing to get data from every "show" Array
{
"score":17.873907,
"show":{
"id":139,
"url":"http://www.tvmaze.com/shows/139/girls",
"name":"Girls",
"type":"Scripted",
"language":"English",
"genres":[
"Drama",
"Romance"
],
"status":"Ended",
"runtime":30,
"premiered":"2012-04-15",
"officialSite":"http://www.hbo.com/girls",
"schedule":{
"time":"22:00",
"days":[
"Sunday"
]
},
"rating":{
"average":6.7
},
"weight":81,
"network":{
"id":8,
"name":"HBO",
"country":{
"name":"United States",
"code":"US",
"timezone":"America/New_York"
}
},
"webChannel":null,
"externals":{
"tvrage":30124,
"thetvdb":220411,
"imdb":"tt1723816"
},
"image":{
"medium":"http://static.tvmaze.com/uploads/images/medium_portrait/31/78286.jpg",
"original":"http://static.tvmaze.com/uploads/images/original_untouched/31/78286.jpg"
},
"summary":"<p>This Emmy winning series is a comic look at the assorted humiliations and rare triumphs of a group of girls in their 20s.</p>",
"updated":1600633829,
"_links":{
"self":{
"href":"http://api.tvmaze.com/shows/139"
},
"previousepisode":{
"href":"http://api.tvmaze.com/episodes/1079686"
}
}
}
}
The Request Code I am using which is giving me the response nicely but i cannot parse the response to JSONObject
Error Showing
org.json.JSONException: Value show of type java.lang.String cannot be
converted to JSONObject
When you are passing JSONObject("show") , it is trying to convert 'show' string to json Obviously it isn't json stirng so it is throwing error;
It should be something like :
JSONObject obj = new JSONObject(response);
JSONObject obj_show= obj.getJSONObject("show"));
Log.d("show",obj_show.getJSONObject("show").toString());
The Solution Was "I Used Nested Model Class to Load Data, and that worked like a charm!"

getJSONArray wrong format for {"GetProdByBizResult":{"TotalCount":4,"RootResults":[{....}]}}"

I successfully get data from wcf web service in my android studio app.
I get this format for the json response.
{"GetProdByBizResult":{"TotalCount":4,"RootResults":[{"catId":1348,"catOrder":1,...
what is the parameter that has to be provide in order to convert it to JSONArray ?
JSONArray jsonArray = jsonResponse.getJSONArray("RootResults");//this doesn't work
I found a workaround by replacing my json string to "RootResults":[{"....}]}"
then
jsonResponse.getJSONArray("RootResults");
is working perfect
{
"GetProdByBizResult": {
"TotalCount": 4,
"RootResults": [
{
"catId": 1348,
"catOrder": 1
}
]
}
}
Json array "RootResults" is a part of json object "GetProdByBizResult" so we need to take "GetProdByBizResult" josn object first and then from this object you can fetch the "RootResults" json array, like
JSONObject jsonObject = jsonResponse.getJSONObject("GetProdByBizResult");
JSONArray jsonArray = jsonObject.getJSONArray("RootResults");

JSON: Treat many objects as array of object

I have a JSON Like this
{ "video":{
"video_3745":{ },
"video_3437":{ },
"video_3471":{ },
"video_4114":{ }
}
}
In which every "video_xxxx" is of the SAME type. Is there a way to treat the "video" field as an array of that type? I need to iterate over all the videos, but the API is not sending them in an array, and I don't know how to model a class to receive this JSON without having to manually specify all the field names...
does GSON or LoganSquare have anything to help me out with this?
Try something like this
JSONObject video= json.getJSONObject("video"); // json is the whole response
Iterator x = video.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(video.get(key));
}
You can't treat them as an array, but with the org.json.JSONObject class you can get the list of keys and iterate over them. I believe in GSON the JsonObject.entrySet method will allow something similar.
https://developer.android.com/reference/org/json/JSONObject.html
https://google.github.io/gson/apidocs/com/google/gson/JsonObject.html

(Android) Java: JSON Parsing

I found a lot of tutorials here, how to parse JSON Data of an JSON Array.
But my JSON File is a little bit complicate (for me). It has the following structure:
JSON File (excerpt)
{
"data": {
"schedule_id": {
"12": {
"name": "CP",
"d_id": [
"7"
]
},
"17": {
"name": "WT",
"d_id": [
"88",
"14"
]
}
}
}
}
Java Code (excerpt)
Info: I've parsed the json into "json" using HTTP GET in another Activity.
JSONObject dataJsonData = json.getJSONObject("data").getJSONObject("schedule_id");
Now I would parse through the ids using a "for"-loop:
ArrayList<String> parsedNameList = new ArrayList<String>();
for (int i = 0; i < idontknow; i++) {
String s = new Integer(i).toString();
parsedNameList.add(dateJsonData.getJSONObject(i).getString("name"));
}
This would add each value of "name" to the ArrayList.
But there are 2 problems:
1. The "schedule_id"s are messed up and incomplete. For example, there is no id "0" and, like in given json, the ids "13, 14, 15, 16" are missing.
2. The "schedule_id"s will be changed every day and will be mixed.
So I don't think, that I can use the predefined integer "i" because some integers aren't a "schedule_id". I could use this loop and would ignore empty entries in the ArrayList, but the JSON contains more than 200 ids - I think it would be more efficient, if there is another way to parse through this json.
I found some informations of the getJSONArray method, but the "d_id"s are Arrays - not the "schedule_ids".
Does anyone has an idea? Is there maybe a placeholder for the parameter of the getString method?
PS: Excuse my english, I'm from germany :)
I think this should work
Iterator keys = dataJsonData.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
String currentDynamicValue = dataJsonData .getString(currentDynamicKey);
parsedJsonList.add(currentDynamicValue );
}
Source: How to parse a dynamic JSON key in a Nested JSON result?
According to your context, it is better to change the json structure,if you have access to web service.
Request for json structure to be like this,
{
"data":{
"schedule":[
{
"id":12,
"name":"CP",
"d_id":[
"7"
]
},
{
"id":12,
"name":"CP",
"d_id":[
"7",
"88"
]
},
{
"id":200,
"name":"AT",
"d_id":[
"7",
"88"
]
}
]
}
}
Otherwise too much iteration can slow down you CPU.

Need help in this Weird JSON

I have a JSON as below
{
"shippingGroupListJson":[
{
"lineId":123,
"shippedTo":{
"country":"US"
},
"cartons":1,
"group":"4",
"shipInscription":{
"municipalInscription":"",
"inscriptionType":"",
"stateInscription":"",
"suframaInscriptionNumber":"",
"inscriptionBranch":"",
"contributorClass":"",
"inscriptionDigit":"",
"inscriptionNumber":""
},
"shipCartonDetails":[
],
"shippedContact":{
"firstName":"Mjjkk",
"email":"nob#gmail.com",
"fax":"--",
"phone":"80-121",
"lastName":"Henry"
},
"mobilityShipStatus":"Not Yet Shipped",
"shipDate":"13 Dec 2014"
},
{
"lineId":0,
"shippedTo":[
],
"cartons":0,
"group":"5",
"shipInscription":[
],
"shipCartonDetails":[
],
"shippedContact":[
],
"mobilityShipStatus":"",
"shipDate":"",
"shipStatus":""
}
]
}
If you see in this above JSON in key "shippedTo", when there is value , I get a JSON Object and when no value is present then i get a Blank JSONArray.
I need to fix this issue. I cannot communicate with the service team to change this as they won't make changes to it. Can any one tell me how can i do the required changes.
I know this is not the rite way, but i need to do something..
I tried using String.replaceAll(oldChar,newChar);
You say you are using GSON, in which case JsonArray and JsonObject are both subclasses of JsonElement.
But you do not say if you are using the DOM or Streaming technique with GSON.
You should show your parsing code, or the class that's being automatically used for the parsing.
In the meantime, based on what you have said, I would define my shippedTo field in my class as an Object. That should parse correctly (if using DOM), and after that you can analyse exactly what you have in that field.
Instead of:
private MyCountryType shippedTo;
Have:
private Object shippedTo;
You could simply check its type at runtime i.e
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
if(js.get("shippedTo") instanceof JSONArray){
//Treat it as an array
}
else{
//Treat it as a single json object
}
}
Furthermore if you need it as an JSONObject immaterial of it being a single element then do this to get your customized string
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
JSONObject js=new JSONObject(json_data);
if(js.get("shippedTo") instanceof JSONArray){
js.put("shippedTo",new JSONObject()); //purge the original array with this new blank element
}
else{
//Do your normal stuff
}
}
String curmodstring=jsPar.toString();
Hope you get the general idea.

Categories

Resources