I am trying Expandable Recycler view using Volley and thoughtbot expandablerecyclerview. Please see my JSON Array below.
{
"Ravi Shankar": [{
"staffname": "Ravi Shankar",
"taskname": "tesing1 task",
"id": "1"
}, {
"staffname": "Ravi Shankar",
"taskname": "testing 2 task",
"id": "2"
}, {
"staffname": "Ravi Shankar",
"taskname": "IMAGE TESTING",
"id": "4"
}, {
"staffname": "Ravi Shankar",
"taskname": "IMAGE NEW",
"id": "5"
}],
"Ritesh": [{
"staffname": "Ritesh",
"taskname": "testing3 task",
"id": "3"
}]
}
This array was group by employee name. I need to get the group name as a string and child array in a loop.
I tried below code but it's not given as I expected.
for(int i=0;i<response.length();i++){
JSONObject jsonObject = response.getJSONObject(i);
String tstaffname = jsonObject.has("staffname")?jsonObject.getString("staffname"):"";
String ttaskname = jsonObject.has("taskname")?jsonObject.getString("taskname"):"";
String tid = jsonObject.has("id")?jsonObject.getString("id"):"";
//addTasks(tstaffname,ttaskname);
Log.e("EmpName", ttaskname);
tasksNames.add(new TasksName(ttaskname));
StaffName staffName = new StaffName(tstaffname, tasksNames);
staffNames.add(staffName);
}
Please comment for any clarification.
Related
I am really new to JSON Parsing and learning everyday.
I have a specific JSON response I have to parse but I am finding no luck doing it.
I am using Volley for Parsing Request.
Here is my response:
{
"error": false,
"message": "Favourties fetched successfully",
"code": 200,
"data": [
{
"id": "5f1980f8c42e1f60854c57e4",
"type": 1,
"status": 1,
"favourite": {
"_id": "5f118057f44ebd1cead089db",
"firstName": "Bilal",
"lastName": "Khan",
"businessName": "Master Paint",
"image": "https://welist-assets.s3.us-west-2.amazonaws.com/profile_images/1592383845941-default_avatar.png"
},
"createdAt": "2020-07-23T12:22:16.731Z",
"updatedAt": "2020-07-23T12:22:16.731Z"
},
{
"id": "5f198084c42e1f60854c57e2",
"type": 3,
"status": 1,
"favourite": {
"images": [],
"_id": "5f12d5345478a53584eca98b",
"name": "Water Paint7"
},
"createdAt": "2020-07-23T12:20:20.680Z",
"updatedAt": "2020-07-23T12:20:20.680Z"
}
]
}
I am able to get the Array which contains 2 object, but I am unable to get the data inside the nested favorites.
try {
Log.d("Onresponse", response);
//converting the string to json array object
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("data");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject favorites = array.getJSONObject(i);
Log.d("lenght", favorites.getString("status"));
//adding the product to product list
favoriteList.add(new FavoriteVendorsModel(
favorites.getString("firstName"),
favorites.getString("lastName"),
favorites.getString("businessName"),
favorites.getString("image")
));
}
Here is my method.
You have skipped one level of nesting. By calling array.getJSONObject(i) you get:
{
"id": "5f1980f8c42e1f60854c57e4",
"type": 1,
"status": 1,
"favourite": {
"_id": "5f118057f44ebd1cead089db",
"firstName": "Bilal",
"lastName": "Khan",
"businessName": "Master Paint",
"image": "https://welist-assets.s3.us-west-2.amazonaws.com/profile_images/1592383845941-default_avatar.png"
},
"createdAt": "2020-07-23T12:22:16.731Z",
"updatedAt": "2020-07-23T12:22:16.731Z"
}
And you are trying to call directly on that object next getString methods:
favorites.getString("firstName");
favorites.getString("lastName");
favorites.getString("businessName");
favorites.getString("image");
When actually you must first get JSONObject named favourite and then call these getString method on it:
JSONObject favorite = favorites.getJSONObject("favourite");
favorite.getString("firstName");
favorite.getString("lastName");
favorite.getString("businessName");
favorite.getString("image");
I am working with Rxandroid and retrofit. I have a json with dynamically changing array name like this,
{
"2016-10-02": [
{
"name": "foo",
"id": "1",
"category": "bar"
},
{
"name": "foo",
"id": "2",
"category": "bar"
},
{
"name": "foo",
"id": "3",
"category": "bar"
},
{
"name": "foo",
"id": "4",
"category": "bar"
}
],
"2016-10-01": [
{
"name": "foo",
"id": "5",
"category": "bar"
},
{
"name": "foo",
"id": "6",
"category": "bar"
},
],
"2016-10-03": [
{
"name": "foo",
"id": "5",
"category": "bar"
}
]
}
The date key name for each array changes automatically and the number of array changes. In this example there are 3 arrays with date key. But the number of these array varies.
I have been through various links in stackoverflow but could not solve the issue.
Use JSONObject keys() to get the key and then you could iterate each key to get the dynamic values :
JSONObject object = new JSONObject("your response string")
Iterator keys = object.keys();
//Let's consider your POJO class is CategoryClass
// Let's take HashMap to store your POJO class for specific KEY
HashMap<String, ArrayList<CategoryClass>> mMap = new HashMap<String, ArrayList<CategoryClass>>();
while(keys.hasNext()) {
// here you will get dynamic keys
String dynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONArray dynamicValue = object.getJSONArray(currentDynamicKey);
//Let's store into POJO Class and Prepare HashMap.
ArrayList<CategoryClass> mCategoryList = new ArrayList<CategoryClass>();
for(int i = 0 ; i < dynamicValue.length(); i++){
CategoryClass mCategory = new CategoryClass();
mCategory.setName(dynamicValue.getString("name"));
mCategory.setId(dynamicValue.getString("id"));
mCategory.setCategory(dynamicValue.getString("category"));
mCategoryList.add(mCategory);
}
//Add Into Hashmap
mMap.put(dynamicKey, mCategoryList);
}
From my point of view,this format is not recommended.The date should be value such as "date":"2016-10-01" instead of json key.
For example : if the given below is json of the person's profile on facebook got thorugh facebook sdk login through android app , How we will get the School Name fron the education Field in th json data in android . Please Help
Data :
{
"id": "1464730016",
"name": "Ravi Tamada",
"first_name": "Ravi",
"last_name": "Tamada",
"link": "https://www.facebook.com/ravi8x",
"username": "ravi8x",
"birthday": "12/22/1988",
"hometown": {
"id": "112158005464147",
"name": "Baruva"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"bio": "Author: www.androidhive.info\r\nCo-author: www.9lessons.info",
"work": [
{
"employer": {
"id": "179366562092719",
"name": "ByteAlly"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"position": {
"id": "124917314217511",
"name": "Product Head"
}
]
}
],
"favorite_athletes": [
{
"id": "18620649907",
"name": "Virat Kohli"
}
],
"education": [
{
"school": {
"id": "131587206873093",
"name": "Raghu Engineering College (REC)"
},
"degree": {
"id": "140065339390579",
"name": "B.Tech"
},
"year": {
"id": "142963519060927",
"name": "2010"
},
"type": "Graduate School",
"classes": [
{
"id": "192259410803415",
"name": "2010",
"with": [
{
"id": "584960408",
"name": "Santosh Patnaik"
}
],
"from": {
"id": "584960408",
"name": "Santosh Patnaik"
}
}
]
}
],
"gender": "male",
"relationship_status": "Single",
"website": "www.androidhive.info\nwww.9lessons.info\nwww.twitter.com/ravitamada\nwww.about.me/rv",
"timezone": 5.5,
"locale": "en_US",
"languages": [
{
"id": "106059522759137",
"name": "English"
},
{
"id": "107617475934611",
"name": "Telugu"
},
{
"id": "112969428713061",
"name": "Hindi"
},
{
"id": "343306413260",
"name": "Tamil"
}
],
"verified": true,
"updated_time": "2012-03-02T17:04:18+0000"
}
JSONObject jsonResult = new JSONObject(jsonUser);
JSONArray data = jsonResult.getJSONArray("education");
if(data != null)
{
for(int i = 0 ; i < data.length() ; i++)
{
JSONObject c = data.getJSONObject(i);
String type = c.getString("type");
if(type.equalsIgnoreCase("college"))
{
JSONObject school = c.getJSONObject("school");
String id2 = school.getString("id");
String name2 = school.getString("name");
JSONObject year = c.getJSONObject("year");
String id_y = school.getString("id");
String name_y = school.getString("name");
}
}
}
Supposing that you've this json into a jsonObject that you retrieve as response, this is the way:
// Get jsonArray 'education' from main jsonObject
JSONArray jsonArrayEducation = jsonObject.getJSONArray("education");
JSONObject jsonSchool = jsonArrayEducation.getJSONObject("school");
Note that if you are interested only at the name, you can group the two lines above into
JSONObject jsonSchool = jsonObject.getJSONArray("education").getJSONObject("school");
// get school name
String schoolName = jsonSchool.getString("name");
I want to get the name of school from this type of json :
"username": "blah",
"education": [
{
"school": {
"id": "[removed]",
"name": "[removed]"
},
"year": {
"id": "[removed]",
"name": "[removed]"
},
"type": "High School"
},
{
"school": {
"id": "[removed]",
"name": "[removed]"
},
"year": {
"id": "[removed]",
"name": "[removed]"
},
"type": "College"
}
]
here is my code :
JSONObject obj=null;
URL img_url;
String jsonUser = facebook.request("me");
obj=Util.parseJson(jsonUser);
String id=obj.optString("id");
String name=obj.optString("name");
what should i write the code to get the education fields school name ?
Facebook fb = new Facebook(API_KEY);// ... login user here ...JSONObject me = new JSONObject(fb.request("me")); String id = me.getString("id");
you can try
var schoolname = yourobject.education.school.name
I decided I wanted to try using the Google shopping API out last week, but I had no idea how to parse JCON objects.
After much searching here I was able to get the product information for an item! However, I cannot narrow down to just a string in the product. So for example I want to just get the title of a product.
I have the following:
jsonString:
{
"kind": "shopping#products",
"etag": "\"GKsxsRlaBDslDpMe-MT1O7wqUDE/dMvQ5Pu2C806fWZJbNJ0GjdesJs\"",
"id": "tag:google.com,2010:shopping/products",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&restrictBy=gtin:051500240908&startIndex=1&maxResults=25",
"totalItems": 3,
"startIndex": 1,
"itemsPerPage": 25,
"currentItemCount": 3,
"items": [
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/7585088/9884865157760252836",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/7585088/gid/9884865157760252836",
"product": {
"googleId": "9884865157760252836",
"author": {
"name": "Southeastern Delivery",
"accountId": "7585088"
},
"creationTime": "2011-07-25T00:15:58.000Z",
"modificationTime": "2012-02-11T09:29:00.000Z",
"country": "US",
"language": "en",
"title": "Jif Peanut Butter, Creamy",
"description": "Jif Creamy Peanut Butter. Fresh Roasted Peanut Taste. Look for the flavor seal. Contains no preservatives. No refrigeration required.",
"link": "http://www.southeasterndelivery.com/Jif_Peanut_Butter_00051500240908/",
"brand": "Jif Peanut Butter",
"condition": "new",
"gtin": "00051500240908",
"gtins": [
"00051500240908"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 15.64,
"shipping": 1.56,
"currency": "USD"
}
],
"images": [
{
"link": "http://www.southeasterndelivery.com/images/ProductImages/00051500240908.jpg"
}
]
}
},
],
"requestId": "0CLGzkcKVo64CFRDd5wod4mMAAA"
}
I have the following code in my android app to parse it:
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray itemsArray = jsonObject.getJSONArray("items");
JSONObject productObject = itemsArray.getJSONObject(0);
//String productTitle = productObject.getString("title");
//tv.setText(productTitle);
tv.setText(productObject.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
tv.setText("JSONOBJECT Error: " + e);
e.printStackTrace();
}
setContentView(tv);
The TextView on my Android app will now display (obviously not indented I did that for easy reading):
"product": {
"googleId": "9884865157760252836",
"author": {
"name": "Southeastern Delivery",
"accountId": "7585088"
},
"creationTime": "2011-07-25T00:15:58.000Z",
"modificationTime": "2012-02-11T09:29:00.000Z",
"country": "US",
"language": "en",
"title": "Jif Peanut Butter, Creamy",
"description": "Jif Creamy Peanut Butter. Fresh Roasted Peanut Taste. Look for the flavor seal. Contains no preservatives. No refrigeration required.",
"link": "http://www.southeasterndelivery.com/Jif_Peanut_Butter_00051500240908/",
"brand": "Jif Peanut Butter",
"condition": "new",
"gtin": "00051500240908",
"gtins": [
"00051500240908"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 15.64,
"shipping": 1.56,
"currency": "USD"
}
],
"images": [
{
"link": "http://www.southeasterndelivery.com/images/ProductImages/00051500240908.jpg"
}
]
}
Now if you notice in my Java code I have two lines commented out. If I uncomment those lines and then comment the line:
tv.setText(productObject.toString());
tv gets set to this error: "JSONOBJECT Error: org.json.JSONEception: No value for title". I am not sure why this is true because clearly their is a title in the productObject.
Any help would be great!
I'm using json-smart in my project. It is very small and very fast. To convert your JSON from Sting to the actual object use JSONObjet json = (JSONObject)JSONValue.parse(rawString);
When you have JSONObject you treat it just like a Map. So String title = (String) json.get("title")
You are missing a level of information in your code. The JSON array contains items, which contains products, which have a title.
Your code should look like:
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray itemsArray = jsonObject.getJSONArray("items");
JSONObject itemObject = itemsArray.getJSONObject(0);
JSONObject productObject = itemObject.getJSONObject("product");
String productTitle = productObject.getString("title");