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
}
Related
I am stuck in fetching data from json api. many times try but result is unsuccessful. Here is json pattern:
{
"All": [{
"MainCategory": {
"AllData": [{
"SubCategory": {
"AllData": [{
"MainBigThumb": "rsz_0_800_CHO1.jpg",
"MainImage": "rsz_0_400_CHO1.jpg",
"MainSmallImages": "rsz_0_100_CHO1.jpg"
}, {
"MainBigThumb": "rsz_0_800_CHO100.jpg",
"MainImage": "rsz_0_400_CHO100.jpg",
"MainSmallImages": "rsz_0_100_CHO100.jpg"
},
{
"MainBigThumb": "rsz_0_800_CHO101.jpg",
"MainImage": "rsz_0_400_CHO101.jpg",
"MainSmallImages": "rsz_0_100_CHO101.jpg"
}
],
"Attribute_Name": "Chocolate",
"Attribute_Value": "123",
"StockKeepingunit": null
}
},
{
"SubCategory": {
"AllData": [{
"MainBigThumb": "rsz_0_800_CRI100.jpg",
"MainImage": "rsz_0_400_CRI100.jpg",
"MainSmallImages": "rsz_0_100_CRI100.jpg"
},
{
"MainBigThumb": "rsz_0_800_CRI101.jpg",
"MainImage": "rsz_0_400_CRI101.jpg",
"MainSmallImages": "rsz_0_100_CRI101.jpg"
}
],
"Attribute_Name": "Crisps",
"Attribute_Value": "124",
"StockKeepingunit": null
}
}
],
"Attribute_Name": "Confectionery",
"Attribute_Value": "122",
"StockKeepingunit": null
}
},
{
"MainCategory": {
"AllData": [{
"SubCategory": {
"AllData": [{
"MainBigThumb": "rsz_0_800_YP100.jpg",
"MainImage": "rsz_0_400_YP100.jpg",
"MainSmallImages": "rsz_0_100_YP100.jpg"
}],
"Attribute_Name": "Sub-Category",
"Attribute_Value": "163",
"StockKeepingunit": null
}
}],
"Attribute_Name": "Your Category",
"Attribute_Value": "162",
"StockKeepingunit": null
}
}
],
"status": {
"message": "success",
"result": 1
}}
the data format is like
1. MainCategory1
1.1 Subcategory1
1.1.1 Product1
1.1.2 Product2
1.2 Subcategory2
1.2.1 Product1
1.2.2 Product2
2. MainCategory2
2.1 Subcategory1
2.1.1 Product1
2.1.2 Product2
You can use retrofit for it and convert your whole json data into Gson, which will make it a lot more easier.
first of all copy the response of your API and create your bean classes through
this site * By clicking source type to JSON * Annotation Style to GSON * Unticking useDoubleNumbers * Unticking AllowAdition Property
then copy those files to your project
then in your activity
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIServiceInterface apiController = retrofit.create(APIServiceInterface.class);
Call<Bean> result = apiController.studentLogin(username,password);
result.enqueue(new Callback<Bean>() {
#Override
public void onResponse(Call<Bean> call, Response<Bean> response) {
// you will get the reponse in the response parameter
}
#Override
public void onFailure(Call<Bean> call, Throwable t) {
}
});
Where APIServiceInterface is the interface file.
It's simple, but you have to be cautious about the {}, [] and , while parsing Json. I will not write parsing code for you, instead just give an idea.
Intitial Json Response Object
Exract JsonArray named as "All" from above object
Get first Position Of above array, you will get an JsonObject
Extract a JsonObject from above object with name "MainCategory"
Exract JsonArray named as "AllData" from above object
Get first Position Of above array, you will get an JsonObject
Extract a JsonObject from above object with name "SubCategory"
Exract JsonArray named as "AllData" from above object
Get first Position Of above array, you will get an JsonObject
Containing following data,
"MainBigThumb": "rsz_0_800_CHO1.jpg",
"MainImage": "rsz_0_400_CHO1.jpg",
"MainSmallImages": "rsz_0_100_CHO1.jpg"
i solved my problem here are json parsing as per below.
JSONObject jsonObj = new JSONObject(json);
JSONArray AllJsonArray = jsonObj.getJSONArray("All");
for (int i = 0; i < AllJsonArray.length(); i++) {
JSONObject AllJsonObject = AllJsonArray.getJSONObject(i);
JSONObject mainCategoryJsonObject = AllJsonObject.getJSONObject("MainCategory");
String mainCategoryName = mainCategoryJsonObject.getString("Attribute_Name");
String mainCategoryValue= mainCategoryJsonObject.getString("Attribute_Value");
JSONArray AllData1JsonArray = mainCategoryJsonObject.getJSONArray("AllData");
for (int j = 0; j < AllData1JsonArray.length(); j++) {
JSONObject AllData1JsonObject = AllData1JsonArray.getJSONObject(j);
JSONObject subCategoryJsonObject = AllData1JsonObject.getJSONObject("SubCategory");
String subCategoryName = subCategoryJsonObject.getString("Attribute_Name");
String subCategoryValue = subCategoryJsonObject.getString("Attribute_Value");
JSONArray AllData2JsonArray = subCategoryJsonObject.getJSONArray("AllData");
for (int k = 0; k < AllData2JsonArray.length(); k++) {
JSONObject AllData2JsonObject = AllData2JsonArray.getJSONObject(k);
String MainBigThumb = AllData2JsonObject.getString("MainBigThumb");
String MainImage = AllData2JsonObject.getString("MainImage");
String MainSmallImages = AllData2JsonObject.getString("MainSmallImages");
}
}
}
{
"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"));
.......
[
{
"subject": "Top exotic beaches in Greece",
"participants": [
"Aristotle", "Socrates"
],
"preview": "Plato,\nThis is what I was talking about for the bachelor party!",
"isRead": false,
"isStarred": true,
"ts": 1471451322,
"id": 5
}
]
How to parse "participants" from this json... thanx in advance
JSONArray jsonArray = new JSONArray(mainJSON.getJSONArray("participants"))
Then you just use your object like this:
jsonArray.getJSONObject(0)
try {
JSONArray participants = jsonObject.getJSONArray("participants")
for (int i = 0; i < participants.length(); i++) {
yourArrayList.add(participants.getString(i))
}
} catch(JSONException e) {
// Handle exception.
}
I get this JSON response from server in my Android application and I want to parse this data by Gson , In Json Response permission tag of my may contains 20-25 data with key like 1, 2,... every value of the permission contains two information separated by # key I have to display only those things which comes into permission in response. Parsed Object Class(Pojo or Model Class must be Parcelable implemented )
My application also support offline feature so, Need suggestion how I can store data in DB at same time when parsing.
[{
"permission": {
"0": "Title#RaqStar",
"1": "Desc#Reader of Raw Star",
"3": "Tytpe#Entertainment",
"4": "Rating#4.5"
},
"id": "233",
"name": "Movie Raw Star"
}, {
"permission": {
"0": "Title#RaqStar",
"3": "Tytpe#Entertainment",
"4": "Rating#4.5"
},
"id": "233",
"name": "Movie Raw Star"
}, {
"permission": {
"1": "Desc#Reader of Raw Star",
"3": "Tytpe#Entertainment",
"4": "Rating#4.5"
},
"id": "233",
"name": "Movie Raw Star"
}, {
"permission": {
"1": "Desc#Reader of Raw Star",
"4": "Rating#4.5"
},
"id": "233",
"name": "Movie Raw Star"
}]
// Whole response array I took as a String "data"
try {
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
responseJSonObj = array.getJSONObject(i);
System.out.println(
generateTitleInfoMap(responseJSonObj.
getJSONObject("permission")));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static HashMap<String, String> generateTitleInfoMap(JSONObject titleInfoMap) {
try {
HashMap<String, String> mapdataVal = new HashMap<String, String>();
if (titleInfoMap.length() > 0) {
Iterator keys = titleInfoMap.keys();
while (keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String) keys.next();
String[] ar = (titleInfoMap.getString(currentDynamicKey)).split("#");
mapdataVal.put(ar[0], ar[1]);
}
}
return mapdataVal;
} catch (JSONException e) {
}
return null;
}
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);