Dynamic object in json - android

I am working on a chat app and have a json response having dynamic objects in that, the dates in chat messages are dynamic. It changes. Please tell me how to make Model Class of this dynamic json. Please Help.
{
"result": 1,
"msg": "Data Found",
"data": {
"user_detail": {
"id": "3",
"first_name": "Rashi",
"last_name": "Singh",
"image_url": "https://res.cloudinary.com/dlnagpsst/image/upload/h_200,w_200/v1658072836/nassibo/9479.jpg"
},
"chat_messages": {
"2022-07-29": [
{
"id": "6",
"chat_id": "4",
"sender_id": "37",
"reciever_id": "3",
"message": "Hii",
"date": "2022-07-29",
"created_at": "2022-07-29 09:58:48",
"user_id": "37"
},
{
"id": "12",
"chat_id": "4",
"sender_id": "37",
"reciever_id": "3",
"message": "Kjhndkhjkdhjk",
"date": "2022-07-29",
"created_at": "2022-07-29 12:58:59",
"user_id": "37"
}
],
"2022-07-30": [
{
"id": "13",
"chat_id": "4",
"sender_id": "37",
"reciever_id": "3",
"message": "Hii",
"date": "2022-07-30",
"created_at": "2022-07-30 12:21:45",
"user_id": "37"
}
]
}
}
}

val b = response.getJSONObject("data").getJSONObject("chat_messages")
for (key in b.keys()) {
Log.i("///// keys",key.toString())
Log.i("///// keys_b",b[key].toString())
val child = b.getJSONArray(key)
for ( i in 0 until child.length()){
val subChild = JSONObject(child.getJSONObject(i).toString())
val id = subChild.getString("id")
val chat_id = subChild.getString("chat_id")
val sender_id = subChild.getString("sender_id")
val message = subChild.getString("message")
val user_id = subChild.getString("user_id")
Log.i("///// child_sub $i :",id)
Log.i("///// child_sub $i :",chat_id)
Log.i("///// child_sub $i :",sender_id)
Log.i("///// child_sub $i :",message)
Log.i("///// child_sub $i :",user_id)
}

Related

how to remove the parameters inside the list ..and make new list android kotlin

I am having a json response and i want store that response of data to room table .i don't need some parameters inside data ( like slug, row_order , tax_id , etc .. ) how to remove that and make new list
{
"data": [
{
"id": "2637",
"row_order": "0",
"name": "Chennai Kichadi Ponni Rice",
"tax_id": "1",
"slug": "chennai-kichadi-ponni-rice-1",
"category_id": "52",
"subcategory_id": "196",
"indicator": "1",
"manufacturer": "",
"made_in": "Chennai Kichadi Ponni Rice",
"return_status": "1",
"cancelable_status": "1",
"till_status": "received",
"image": "http://www.pasumai.co.in/upload/images/5718-2021-12-18.png",
"status": "1",
"popular": "0",
"date_added": "2021-12-18 06:26:12",
"return_max_days": "0",
"tax": "0",
"price": "1599",
"tax_title": "GST",
"tax_percentage": "0",
"is_favorite": false,
"is_notify_me": false,
"variants": [
{
"id": "4726",
"product_id": "2637",
"cart_count": "0",
"is_notify_me": false
}
]
},
{
"id": "2648",
"row_order": "1",
"name": "Double Deer Basmati Rice Gold",
"tax_id": "9",
"slug": "double-deer-basmati-rice-gold",
"category_id": "52",
"subcategory_id": "196",
"indicator": "1",
"manufacturer": "",
"made_in": "Double Deer Basmati Rice Gold",
"return_status": "1",
"cancelable_status": "1",
"till_status": "received",
"image": "http://www.pasumai.co.in/upload/images/3330-2021-12-21.png",
"status": "1",
"popular": "0",
"date_added": "2021-12-19 00:23:28",
"return_max_days": "0",
"tax": "5",
"price": "279",
"tax_title": "GST",
"tax_percentage": "5",
"is_favorite": false,
"is_notify_me": false,
"variants": [
{
"id": "4755",
"product_id": "2648",
"cart_count": "0",
"is_notify_me": false
}
]
}
]
}
I want the new list as like this
{
"data": [
{
"id": "2637",
"name": "Chennai Kichadi Ponni Rice",
"subcategory_id": "196",
"image": "http://www.pasumai.co.in/upload/images/5718-2021-12-18.png",
"is_favorite": false,
},
{
"id": "2648",
"name": "Double Deer Basmati Rice Gold",
"subcategory_id": "196",
"image": "http://www.pasumai.co.in/upload/images/3330-2021-12-21.png",
"is_favorite": false,
}
]
}
Is there any method to filter ?? if yes ..please explain me with code
i want to add the new list to room table...so that i need to cut some unwanted parameters . i don't know how to do that
You need to deserialize JSON to object, for deserialization you can use
com.google.gson add to gradle:
dependencies {
implementation 'com.google.code.gson:gson:2.9.1'
}
create your data class
data class Order(
val id:String,
val name:String,
val image: String,
#SerializedName("subcategory_id")
val subcategoryId: String,
#SerializedName("is_favorite")
val isFavorite: Boolean
)
and finally deserialize your incoming data from network
val responseFromNetwork = getDataFromNetwork() //here you get your json from network
val gson = Gson()
val ordersType = object : TypeToken<List<Order>>() {}.type
val itemList = gson.fromJson<List<Order>>(responseFromNetwork , ordersType)// will be deserialized only field what are in data class another one will be ignored
and finally add to DB your data

How to fetch data from a nested array?

I have to fetch the value from an array nested inside another array. I can fetch values from the first array but not able to fetch values from the second array.
I am able to read the values from the main array but I am unable to read the values from the array which is nested inside it.
JSONObject jsono = new JSONObject(res);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++)
{
JSONObject object = jarray.getJSONObject(i);
JSONArray jarray1 = object.getJSONArray("comments_data");
for (int j = 0; j < jarray1.length(); j++)
{
JSONObject object1 = jarray1.getJSONObject(j);
String Namee = object1.getString("username");
String Ratingg = object1.getString("rating");
String Commentt = object1.getString("comment");
Comments comments1 = new Comments();
comments1.setUsername(Namee);
comments1.setRating(Ratingg);
comments1.setComments(Commentt);
comments1.setProfileimage(R.drawable.fav);
commentsList.add(comments1);
}
}
And this is my json.
{
"status": "success",
"msg": " Menu Details",
"data": [
{
"id": "1",
"rest_id": "1",
"menu_rate": "100",
"collection_time": "2:22pm",
"quantity_left": "3",
"food_type": "veg",
"img1": "",
"img2": "",
"img3": "",
"date": "",
"menu_name": "",
"comments_data": [
{
"id": "20",
"user_id": "127",
"res_id": "1",
"comment": "shreyansh s",
"date": "0000-00-00 00:00:00",
"rating": "0.0",
"username": "lucky",
"userimage": "123"
},
{
"id": "19",
"user_id": "126",
"res_id": "1",
"comment": "das",
"date": "0000-00-00 00:00:00",
"rating": "3.0",
"username": "shrey srivastava",
"userimage": "123"
},
{
"id": "18",
"user_id": "126",
"res_id": "1",
"comment": "",
"date": "0000-00-00 00:00:00",
"rating": "3.0",
"username": "shrey srivastava",
"userimage": "123"
},
{
"id": "17",
"user_id": "126",
"res_id": "1",
"comment": "sakjbdkjasbk",
"date": "0000-00-00 00:00:00",
"rating": "3.0",
"username": "shrey srivastava",
"userimage": "123"
},
{
"id": "16",
"user_id": "107",
"res_id": "1",
"comment": "hello",
"date": "0000-00-00 00:00:00",
"rating": "5",
"username": "shreyansh",
"userimage": ""
},
{
"id": "15",
"user_id": "107",
"res_id": "1",
"comment": "hello",
"date": "0000-00-00 00:00:00",
"rating": "5",
"username": "shreyansh",
"userimage": "123"
},
{
"id": "14",
"user_id": "107",
"res_id": "1",
"comment": "hello",
"date": "0000-00-00 00:00:00",
"rating": "5",
"username": "shreyansh",
"userimage": "123"
},
{
"id": "6",
"user_id": "82",
"res_id": "1",
"comment": "good",
"date": "0000-00-00 00:00:00",
"rating": "",
"username": "jaim",
"userimage": "google.com"
}
]
}
]
}
Note carefully how you JSON is built.
First, you have to query for "data". You get JSON-Array. So you traverse it by the indices.
Hence, you query for the specific index in "data" (you can use a loop, of course).
For each iteration, you get a JSONObject, and in it you query for "comments_data".
String json = "{ \"status\": \"success\", \"msg\": \" Menu Details\", \"data\": [ { \"id\": \"1\", \"rest_id\": \"1\", \"menu_rate\": \"100\", \"collection_time\": \"2:22pm\", \"quantity_left\": \"3\", \"food_type\": \"veg\", ...
JSONObject object = new JSONObject(json);
JSONObject jarray1 = jarray_data.getJSONObject(0);
JSONArray comments = jarray1.getJSONArray("comments_data");

Set data in expandable listview android form JSON format

I have following pattern of JSON
{
"menu": [{
"id": "74",
"parent_id": "0",
"title": "Mobiles & Tablets",
"menu_type": "7",
"menu_icon_image": "",
"link": "#",
"childs": [{
"id": "75",
"parent_id": "74",
"title": "Mobile Phones",
"menu_type": "7",
"menu_icon_image": "",
"link": "categories/mobile-tablets"
}, {
"id": "76",
"parent_id": "74",
"title": "Mobile Accessories",
"menu_type": "7",
"menu_icon_image": "",
"link": "#"
}, {
"id": "77",
"parent_id": "74",
"title": "Tablets",
"menu_type": "7",
"menu_icon_image": "",
"link": "#"
}, {
"id": "78",
"parent_id": "74",
"title": "Audio & Video",
"menu_type": "7",
"menu_icon_image": "",
"link": "#"
}, {
"id": "79",
"parent_id": "74",
"title": "Laptops",
"menu_type": "7",
"menu_icon_image": "",
"link": "#"
}]
}, {
"id": "80",
"parent_id": "0",
"title": "WOMEN",
"menu_type": "7",
"menu_icon_image": "",
"link": "#",
"childs": [{
"id": "81",
"parent_id": "80",
"title": "GIRLS CLOTHING",
"menu_type": "7",
"menu_icon_image": "",
"link": "categories/womens-clothing"
}]
}],
"slider": [{
"id": "56",
"url": "#",
"default_image": "https://s3.amazonaws.com/atbdev/cache/advertis_img/1-fl-itwQr56f76f6df2bea.png/88e5b614324080684af061c510496d29",
"title": "Mobile Test Slider",
"image": null,
"days": null
}, {
"id": "55",
"url": "#",
"default_image": "https://s3.amazonaws.com/atbdev/cache/advertis_img/1-fl-uIXFZ56f76efbcd627.png/e5a0e22dcb0de1007c88c16db1aebb7f",
"title": "Mobile Test Slider",
"image": null,
"days": null
}, {
"id": "52",
"url": "#",
"default_image": "https://s3.amazonaws.com/atbdev/cache/advertis_img/1-fl-QULkY56f7719eb0915.png/a4d0065b56b57b7d01d44873bbdb1df8",
"title": "Mobile Test Slider",
"image": null,
"days": null
}, {
"id": "51",
"url": "#",
"default_image": "https://s3.amazonaws.com/atbdev/cache/advertis_img/1-fl-L0ROK56f7716acccf0.png/e194ea4403c4b4b7e17f1fecfa329f22",
"title": "Mobiles & Tablets",
"image": null,
"days": null
}, {
"id": "1",
"url": "",
"default_image": "https://s3.amazonaws.com/atbdev/cache/advertis_img/1-fl-qtvVk56f60fd0379b9.jpg/510c150029fd29d1d77b869d837b126e",
"title": "Slider Add",
"image": null,
"days": null
}],
"advertise": [{
"id": "54",
"usrl": "categories/mobile-tablets",
"default_image": "https://s3.amazonaws.com/atbdev/cache/advertis_img/1-fl-IWkmH56f66a2b60bde.jpg/05571c3c78954e1a461b87bd62698273",
"title": "Mobile phone home page advertise",
"image": null,
"days": null
}, {
"id": "53",
"usrl": "categories/mobile-tablets",
"default_image": "https://s3.amazonaws.com/atbdev/cache/advertis_img/3-fl-YK1pI56f5102a7237b.png/118b3074314006a62a7f10867a447be6",
"title": "Mobile phone home page advertise",
"image": null,
"days": null
}]
}
List<ExpanTitelandTotal> result1111 = new ArrayList<ExpanTitelandTotal>();
for (int i = 0; i < menuArrayList.size(); i++) {
ExpanTitelandTotal mExpanTitelandTotal11 = new ExpanTitelandTotal();
mExpanTitelandTotal11.setTitle(menuArrayList.get(i).getTitle());
mExpanTitelandTotal11.setLink(menuArrayList.get(i).getLink());
mExpanTitelandTotal11.setId(Integer.parseInt(menuArrayList.get(i).getId()));
//result1111.add(mExpanTitelandTotal11);
if (mGetDrawerAndHome.getMenu().get(i).getChilds().size() > 0) {
mExpanTitelandTotal11.setIsMultiple(true);
Log.d("mGetDrawerAndHome.getMenu().get(i).getChilds().size() ",String .valueOf(mGetDrawerAndHome.getMenu().get(i).getChilds().size()));
for (int j = 0; j < mGetDrawerAndHome.getMenu().get(i).getChilds().size(); j++)
{
Log.d("Sub Menu", mGetDrawerAndHome.getMenu().get(i).getChilds().get(j).getTitle());
ExpanTitelandTotal mExpanTitelandTotal = new ExpanTitelandTotal();
mExpanTitelandTotal.setTitle(mGetDrawerAndHome.getMenu().get(i).getChilds().get(j).getTitle());
mExpanTitelandTotal.setLink(mGetDrawerAndHome.getMenu().get(i).getChilds().get(j).getLink());
mExpanTitelandTotal.setId(Integer.parseInt(mGetDrawerAndHome.getMenu().get(i).getChilds().get(j).getId()));
result1111.add(mExpanTitelandTotal);
}
} else {
mExpanTitelandTotal11.setIsMultiple(false);
}
mExpanTitelandTotal11.setItemList(result1111);
mArrayListExpanTitelandTotals.add(mExpanTitelandTotal11);
}
listAdapterTNA = new ExpandableListAdapterTNA(ActivityDrawer.this, mArrayListExpanTitelandTotals, mExpandableListView);
mExpandableListView.setAdapter(listAdapterTNA);
mExpandableListView.setIndicatorBounds(10, 80);
mExpandableListView.setDivider(null);
above is my code and when i run this i get following output
In expandable list view two different category data store in all main category data ? any idea how can i solve this ?
Create a new List object inside the first for loop sentence:
List<ExpanTitelandTotal> result1111;
for (int i = 0; i < menuArrayList.size(); i++) {
result1111 = new ArrayList<ExpanTitelandTotal>();
/////YOUR CODE
}

How to loop through a dynamic json key in a nested json object in android

I am developing a quiz application and my questions are in a Json file
{
"name": "JHS ASANTE TWI",
"course_id": "73",
"courseID": "01JS88",
"package_code": "JHS",
"description": "",
"category": "",
"author": "content#exams.com",
"questions": {
"58242": {
"qid": "58242",
"topic": "1268",
"instructions": "Yi nea εne nea yεasensane aseε no asekyerε bɔ abira",
"text": "<p>Kofi de sika no maa <span style=\"text-decoration: underline;\">aberante<span>ε</span></span> bi.</p>",
"resource": "",
"qtype": "SINGLE",
"confirmed": "1",
"public": "1",
"flagged": "0",
"updated_at": "2014-07-10 12:29:33",
"rating": 0,
"answers": [
{
"id": "250310",
"text": "<p>ababaawa</p>",
"value": "1",
"solution": ""
},
{
"id": "250311",
"text": "<p>ab<span>ɔfra</span><span><br /></span></p>",
"value": "0",
"solution": ""
},
{
"id": "250312",
"text": "<p>aberewa</p>",
"value": "0",
"solution": ""
},
{
"id": "250313",
"text": "<p>abarimaa</p>",
"value": "0",
"solution": ""
}
]
},
"58245": {
"qid": "58245",
"topic": "1268",
"instructions": "Yi nea εne nea yεasensane aseε no asekyerε bɔ abira",
"text": "<p>Mehunuu m'adamfo bi nnora <span style=\"text-decoration: underline;\">an</span><span style=\"text-decoration: underline;\">ɔpa</span>.</p>\n<p> </p>\n<p> </p>",
"resource": "",
"qtype": "SINGLE",
"confirmed": "1",
"public": "1",
"flagged": "0",
"updated_at": "2014-07-10 12:43:29",
"rating": 0,
"answers": [
{
"id": "250329",
"text": "<p>awia</p>",
"value": "1",
"solution": ""
},
{
"id": "250328",
"text": "<p>anwummer<strong></strong>ε</p>",
"value": "0",
"solution": ""
},
{
"id": "250327",
"text": "<p>ahemadakye</p>",
"value": "0",
"solution": ""
},
{
"id": "250326",
"text": "<p>owigyinaeε</p>",
"value": "0",
"solution": ""
}
]
},
"58246": {
"qid": "58246",
"topic": "1268",
"instructions": "Yi nea εne nea yεasensane aseε no asekyerε bɔ abira",
"text": "<p>Asomaning <span style=\"text-decoration: underline;\">kuro</span> no so.</p>",
"resource": "",
"qtype": "SINGLE",
"confirmed": "1",
"public": "1",
"flagged": "0",
"updated_at": "2014-07-10 12:53:00",
"rating": 0,
"answers": [
{
"id": "250330",
"text": "<p><span>ɔmansini</span></p>",
"value": "0",
"solution": ""
},
{
"id": "250331",
"text": "<p><span>ɔman</span></p>",
"value": "0",
"solution": ""
},
{
"id": "250332",
"text": "<p>wiase</p>",
"value": "0",
"solution": ""
},
{
"id": "250333",
"text": "<p>akuraa</p>",
"value": "1",
"solution": ""
}
]
}
}
}
My question is: how do I access the next question of "questions" when i click next for the next question since "58242", "58245", etc are all dynamic values?
the answer on this post was very helpfull but now i want to now how loop through the questions How to parse a dynamic JSON key in a Nested JSON result
it helped me get the currentdynamic value but does not give me the next question when i click on next
private View.OnClickListener nextListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
try {
if (quesIndex != searchResult.getJSONObject("questions").length() - 1) {
quesIndex++;
progress.setProgress(0);
progress.setMax(100);
} else {
Intent myIntent = new Intent(TestActivity.this, Assesment.class);
myIntent.putExtra("intVariableName", score);
startActivity(myIntent);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (quesIndex == searchResult.getJSONObject("questions").length() - 1) {
next.setText("Finish");
Intent myIntent = new Intent(TestActivity.this, Assesment.class);
myIntent.putExtra("intVariableName", score);
startActivity(myIntent);
// close this activity
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
showQuestion(quesIndex, review);
}
};
will appreciate the help thanks :)
Not sure what you problem is. Seems like the solution is in the link you gave above.
JSONObject questions = result.getJSONObject("questions");
Iterator keys = questions.keys();
//go through every question
while (keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
JSONObject currentQuestion = questions.getJSONObject(currentDynamicKey);
}

Facebook Profile Information JSON Parsing in Android

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");

Categories

Resources