JSONArray strange behavior for different API Versions - android

I have a problem with JSONArray. My JSONArray works on API 22 but not on a device with API less than 22.
When I change my compile sdk I get tons of errors.
Is there any solution for this strange behavior. I can't explain it...
This is the JSON:
{"2":"[{\"id\":\"3\",\"value\":\"1.15\",\"name\":\"Knobi\"}, Dressing]","1":"[{\"id\":\"1\",\"value\":\"0.00\",\"name\":\"Scharf\"}, Soße, {\"id\":\"2\",\"value\":\"1.00\",\"name\":\"Tzatziki\"}, Soße]"}
if(addonsJSON != null)
{
Iterator<String> iterator = addonsJSON.keys();
while (iterator.hasNext())
{
String theKey = iterator.next();
System.out.println(addonsJSON.get(theKey));
JSONArray values = addonsJSON.getJSONArray(theKey);
for (int j = 0; j < values.length(); j+=2)
{
JSONObject vals = new JSONObject(values.getString(j));
CartChild cartChild = new CartChild();
cartChild.name = vals.getString("name");
cartChild.price = vals.getString("value");
itemtotal += Float.parseFloat(vals.getString("value"));
childsList.add(cartChild);
}
}
}

your json is not a valid json text. You can't iterate over invalid json
modify it like that
{
"1": [
{
"id": "1",
"value": "0.00",
"name": "Scharf"
},
"Soße",
{
"id": "2",
"value": "1.00",
"name": "Tzatziki"
},
"Soße"
],
"2": [
{
"id": "3",
"value": "1.15",
"name": "Knobi"
},
"Dressing"
]
}
compare your json and mine on http://jsonlint.com/

The problem was that I convert the HashMap to a JSONObject. After that I saved my JSONObject as a String to SugarORM. The convertion was the fault!
So I tried it with GSON. Now it works.
So just use this:
Gson gson = new Gson();
String json = gson.toJson(hashmap);

Related

How to get specific data from API request without creating data classes including other data classes?

for example:
{
"error": false,
"message": "",
"code": "",
"ver": "v1.0.0",
"base": "https://,,,,,,,,,.com/",
"count": 1,
"updated": "2020-10-28T19:40:51+03:00",
"data": [
{
"id": "44",
"slug": "human-resources",
"name": "Human resources",
"img1": null,
"img2": "page_44/1560347480_2.jpg",
"date": "2019-05-31",
"des": "'vvvvvv.v",
"sendMail": "info#....",
"iframe_url": "ff/ff"
}
]
}
this is api json response.
I want only "data": [] value, not the rest.
Is there a way I can avoid creating data class for whole api response instead just request "data": [..] value?
I am using Android Studio Kotlin Retrofit Moshi
If I understand your question correctly, you just want to extract data from that JSON string. You can do that with:
JSONArray dataArray;
try {
dataArray = new JSONObject(yourString).optJSONArray("data");
} catch (JSONException e) {
// whatever
}
for (int i = 0; i < dataArray.length(); ++i) {
// do whatever you want with each object:
String name = dataArray.optJSONObject(i).optString("name");
}

how to get 1st array value

{
"status": "true",
"data": [
{
"giid": "91",
"gid": "26",
"name": "gallery/image/7475068.png",
"type": "0",
"singer": ""
},
{
"giid": "92",
"gid": "25",
"name": "gallery/image/8704185.png",
"type": "0",
"singer": ""
},
{
"giid": "93",
"gid": "25",
"name": "gallery/image/3639377.png",
"type": "0",
"singer": ""
},
{
"giid": "94",
"gid": "25",
"name": "gallery/image/5589478.png",
"type": "0",
"singer": ""
},
{
"giid": "95",
"gid": "25",
"name": "gallery/image/3503162.png",
"type": "0",
"singer": ""
}]}
get only first value in my list view how its possible?
my code :-
try {
JSONArray jsonObject = response.getJSONArray("data");
for (int i = 0; i < jsonObject.length(); i++) {
System.out.println("<<<<<<<<<<<<<<<<<<<");
JSONObject object1 = jsonObject.getJSONObject(i);
Beans_News info = new Beans_News();
info.setDate(object1.getString("giid"));
info.setNews(object1.getString("name"));
info.setNewsid(object1.getString("gid"));
info.setStatus(object1.getString("type"));
array_bean.add(info);
lvls.setAdapter(new CustomAdapter_classwork());
pDialog.hide();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Not available", Toast.LENGTH_SHORT).show();
e.printStackTrace();
pDialog.hide();
}
i want only first value in my list please help me
If you send response like:
res.send({'status':'true', 'data': data})
or
res.json({'status':'true', 'data': data})
and this data is a array then you can get 1st element like
obj = response;
let arr= obj.data;
if(arr.length>0) firstElement = arr[0]
else //whatever you want
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray jArray = jsonObject.getJSONArray("data");
//remove for loop if you only need single data
//for (int i = 0; i < jArray.length(); i++) {
//if you need first value set 0 in index
JSONObject object1 = jArray.getJSONObject(0);
info.setDate(object1.getString("giid"));
info.setNews(object1.getString("name"));
info.setNewsid(object1.getString("gid"));
info.setStatus(object1.getString("type"));
try this hope it helps
Made Changes here
JSONObject object1 = jsonObject.getJSONObject(0);
Use 0 index
update your code like this
JSONObject jsonObject = response.getJSONArray("data").getJSONObject(0);
Beans_News info = new Beans_News();
info.setDate(jsonObject.getString("giid"));
info.setNews(jsonObject.getString("name"));
info.setNewsid(jsonObject.getString("gid"));
info.setStatus(jsonObject.getString("type"));
this is the simplest code you can try to achieve your task.
Just set .getJSONObject(0);
JSONObject object1 = jsonObject.getJSONObject(0); // Set 0 for First Value
Beans_News info = new Beans_News();
info.setDate(object1.getString("giid"));
info.setNews(object1.getString("name"));
info.setNewsid(object1.getString("gid"));
info.setStatus(object1.getString("type"));
.......

Count the json objects inside json Array in Android?

I am trying to parse json values into my Android application. Here i am stuck at a place wherein I need to have the objects length inside the json arraylist.
Below is my json:
"events": { //json object
"2012-11-30": [ // json array
{
"privacy": "OPEN",
"name": "LOGDGE"
}
],
"2013-08-17": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-14": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-27": [
{
"privacy": "OPEN",
"name": "Salsa Party!"
}
{
"privacy": "OPEN",
"name": "Dance Performance Course",
}
],
"2013-10-23": [
{
"privacy": "OPEN",
"name": "Dance Performance Course"
}
]
}
Now my question is how do I parse to get the length of the json array like:
2012-11-30 count = 1
2013-08-17 count = 1
2013-09-27 count = 2
How do I loop the json array using the date's as they are json object and find the length of each of the json array dates. I want count of each array individually over here.
Would I need to add a key value kind of pair in the json array "dates" so as I can have a for loop to get the count of the values inside the array?
Thank you in advance
Try Below Code and count objects using length of JsonArray:
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String key = keys.next();
try{
JSONArray array = jObject.getJSONArray(key);
//count objects values using array length.
}
catch(Exception e){
e.printStackTrace()
}
}
String jstr = jso.getString("Events");
JSONObject mdcalkey = new JSONObject(jstr);
Iterator iter = mdcalkey.keys();
ArrayList<String> arr = new ArrayList<String>();
ArrayList<String> arrTimeDate = new ArrayList<String>();
ArrayList<String> arrtype = new ArrayList<String>();
while (iter.hasNext()) {
arr.add((String) iter.next());
}
// ja = mdcalkey.getJSONArray(arr.get(0));
jar = new JSONArray[arr.size()];
This arr array will display all dates array..please check it..if any query then tell me.
You can iterate over the keys in your JSONObject and check if their corresponding values are JSONArrays, then store their lengths in a map:
Iterator iter = yourJSONObject.keys();
while (iter.hasNext())
{
String key = (String) iter.next();
JSONArray array = yourJSONObject.optJSONArray(key);
if (array != null)
{
// the value for this key is an array
for (int i = 0; i < array.length; i++){
// do stuff
}
}
}
String json = "events": { //json object
"2012-11-30": [ // json array
{
"privacy": "OPEN",
"name": "LOGDGE"
}
],
"2013-08-17": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-14": [
{
"privacy": "OPEN",
"name": "Party: Dinner and Dancing"
}
],
"2013-09-27": [
{
"privacy": "OPEN",
"name": "Salsa Party!"
}
{
"privacy": "OPEN",
"name": "Dance Performance Course",
}
],
"2013-10-23": [
{
"privacy": "OPEN",
"name": "Dance Performance Course"
}
]
}
try {
JSONObject obj = new getJSONObject(new JSONObject("{"+"json"+"}").getJSONObject("events").toString());
Iterator iterator = obj.keys();
while (iterator.hasNext())
{
String key = (String) iterator.next();
JSONArray array = obj.optJSONArray(key);
if (array != null)
{
// the value for this key is an array
for (int i = 0; i < array.length; i++){
// do stuff
}
}
}
}
catch (JSONException e)
{
// handle exception here
}

how to parse json array without "id"

Below is my code which parse JSON if I fetch "id". If I don't give id then the JSON array will not show. How do i show JSON without id?
How do I parse JSONArray without "id" if I don't give id in JSON file then array will not show it is necessary to give "id" in JSON file???
this json array not show
{
"status": 1,
"data": [
{
"title": "Elementary"
},
{
"title": "Middle"
},
{
"title": "High"
},
{
"title": "Atypical"
}
]
}
this json array will show
{
"status": 1,
"data": [
{
"id": "1",
"title": "Elementary"
},
{
"id": "2",
"title": "Middle"
},
{
"id": "3",
"title": "High"
},
{
"id": "4",
"title": "Atypical"
}
]
}
Code:
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
// Category_ID.add(Long.parseLong(object.getString("id")));
Category_name.add(object.getString("title"));
}
You are accessing the id property here:
Category_ID.add(Long.parseLong(object.getString("id")));
When it is not there this will throw an exception.
Try This Code while parsing your json:
if(object.has("id"))
{
Category_ID.add(Long.parseLong(object.getString("id")));
}
else
{
// add default id
}
hope this will work for you.
I suppose you want your code to work for both JSON samples.
You can perform a check if "id" exists or not and then parse accordingly.
You can perform this check using the below code.
String id = object.optString("id");
//JSONObject.optString("id") will return id's value if it exists or else will return empty string.
if(!"".equals(id)){
Category_ID.add(Long.parseLong(id));
//this code will run only when your JSON contains id
}
else
{
//this code will run when your JSON doesn't have id field.
Category_ID.add();
}

How to parse this JSON data using GSON? and put it into an ArrayList

I am trying to parse data from a MongoDB cloud server. My JSON data returned from the server is as follows:
[
{
"_id": {
"$oid": "4e78eb48737d445c00c8826b"
},
"message": "cmon",
"type": 1,
"loc": {
"longitude": -75.65530921666667,
"latitude": 41.407904566666666
},
"title": "test"
},
{
"_id": {
"$oid": "4e7923cb737d445c00c88289"
},
"message": "yo",
"type": 4,
"loc": {
"longitude": -75.65541383333333,
"latitude": 41.407908883333334
},
"title": "wtf"
},
{
"_id": {
"$oid": "4e79474f737d445c00c882b2"
},
"message": "hxnxjx",
"type": 4,
"loc": {
"longitude": -75.65555572509766,
"latitude": 41.41263961791992
},
"title": "test cell"
}
]
The problem I am having is the data structure returned does not include a name of the array of JSON objects. Each object returned is a "post". But how do I parse it using GSON if the there is no name for the array of JSON objects. I would like to put these "posts" into an ArrayList of type Post.
Piece of code you are looking for:
String jsonResponse = "bla bla bla";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = (List<Post>) gson.fromJson(jsonResponse, listType);
Use the contructor for JSONArray to parse the string:
//optionally use the com.google.gson.Gson package
Gson gson = new Gson();
ArrayList<Post> yourList = new ArrayList<Post>();
String jsonString = "your string";
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++){
Post post = new Post();
//manually parse for all 5 fields, here's an example for message
post.setMessage(jsonArray.get(i).getString("message"));
//OR using gson...something like this should work
//post = gson.fromJson(jsonArray.get(i),Post.class);
yourList.Add(post);
}
Considering there are only 5 fields, using Gson might be more overhead than you need.

Categories

Resources