How to parse json with dynamic keys using Retrofit 2.0? - android

Here's the JSON where jsonObject key is dynamic :
{
"CH000032": [
{
"type": "event",
"details": {
"programID": "MV10000032",
"programType": "MOVIE",
"title": "Titanic",
"year": "1997",
"rating": "PG-13",
"durationSec": 11640,
"startTimeSec": "",
"endTimeSec": "",
"language": "ENG",
"isHD": true,
"Genres": [
"Movies",
"Action"
],
"description": "A seventeen-year-old aristocrat falls in love with a kind but poor artist aboard the luxurious, ill-fated R.M.S. Titanic.",
"imageUrl": "http://res.cloudinary.com/dte07foms/image/upload/c_scale,h_405,w_270/l_Copyright_e3jt1k/v1508831090/Titanic_b0hqo0.jpg"
}
}
],
"CH000033": [
{
"type": "event",
"details": {
"programID": "EP10000132",
"programType": "EPISODE",
"title": "A Chic Bar in Ibiza",
"seriesTitle": "Two and a Half Men",
"seasonNumber": 12,
"epsiodeNumber": 2,
"year": "2014",
"rating": "TV-14",
"durationSec": 1260,
"startTimeSec": "",
"endTimeSec": "",
"language": "ENG",
"isHD": true,
"Genres": [
"Comedy",
"Romance"
],
"description": "Alan has second thoughts about getting married when Walden has him sign a prenup.",
"imageUrl": "http://res.cloudinary.com/dte07foms/image/upload/c_crop,h_405,w_270//l_Copyright_e3jt1k/v1508831090/2AndHalfmen_splkro.jpg"
}
}
]
}
I would like to parse this JSON. Please let me know how should the class
be written with #SerializedName annotation using Retrofit.
Note : CH000032, CH000033 etc are dynamic.

You can use Map<String, ModelClassName> in your model class for dynamic like below :-
public class Data {
#SerializedName("your_key")
#Expose
private Map<String, ModelClassName> result;
//....
}
this can help to parse dynamic key in retrofit.

What you are asking will take much work , instead a better approach will be to change the structure o json to something like this -
"data": [
{
"type": "event",
"programID": "MV10000032",
"programType": "MOVIE",
"title": "Titanic",
"year": "1997",
"rating": "PG-13",
"durationSec": 11640,
"startTimeSec": "",
"endTimeSec": "",
"language": "ENG",
"isHD": true,
"Genres": [
"Movies",
"Action"
],
"description": "A seventeen-year-old aristocrat falls in love with a kind but poor artist aboard the luxurious, ill-fated R.M.S. Titanic.",
"imageUrl": "http://res.cloudinary.com/dte07foms/image/upload/c_scale,h_405,w_270/l_Copyright_e3jt1k/v1508831090/Titanic_b0hqo0.jpg"
},
{
"type": "event",
"programID": "MV10000032",
"programType": "MOVIE",
"title": "Titanic",
"year": "1997",
"rating": "PG-13",
"durationSec": 11640,
"startTimeSec": "",
"endTimeSec": "",
"language": "ENG",
"isHD": true,
"Genres": [
"Movies",
"Action"
],
"description": "A seventeen-year-old aristocrat falls in love with a kind but poor artist aboard the luxurious, ill-fated R.M.S. Titanic.",
"imageUrl": "http://res.cloudinary.com/dte07foms/image/upload/c_scale,h_405,w_270/l_Copyright_e3jt1k/v1508831090/Titanic_b0hqo0.jpg"
}]

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

Retrofit Android API Get without nested array

This is my first android project (I'm a php developer) but i'm struggling to see how to take this example which uses a nested structure under data for the json array whereas my data is not double nested like this example.
The excample code I am trying to modify is from here https://github.com/datanapps/RetrofitKotlin and the key differences in the json are todo with the nesting.
Original
{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"email": "george.bluth#reqres.in",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://reqres.in/img/faces/1-image.jpg"
},
{
"id": 2,
"email": "james.smith#reqres.in",
"first_name": "James",
"last_name": "Smith",
"avatar": "https://reqres.in/img/faces/1-image.jpg"
}
]
}
whereas mine is simply
[
{
"_id": "62f4cb4e131d9d00046a1b9c",
"device": "AndroidAPS-DexcomG6",
"date": 1660209967000,
"dateString": "2022-08-11T09:26:07.000Z",
"isValid": true,
"sgv": 133,
"direction": "Flat",
"type": "sgv",
"created_at": "2022-08-11T09:26:38.326Z",
"mills": 1660209998326
},
{
"_id": "62f4cb4e131d9d00046a1b9c",
"device": "AndroidAPS-DexcomG6",
"date": 1660209967000,
"dateString": "2022-08-11T09:26:07.000Z",
"isValid": true,
"sgv": 133,
"direction": "Flat",
"type": "sgv",
"created_at": "2022-08-11T09:26:38.326Z",
"mills": 1660209998326
}
]
Specifically I want to query the SGV values, direction and date
Thanks
You "return type" of "method" in Retrofit "interface" will be:
List<MyModel>
And MyModel:
data class MyModel(val _id:String, val device:String,...)

Handle custom response in Paging library 3 Android

I am new to the Paging 3 library in android kotlin. I want unlimited data. So I found the Paging 3 library helpful in my case. I used PagingSource to create a list. I am not using Room. I have multiple view in recyclerView. I am using PagingDataAdapter with diff util for my Recyclerview. I used the recommended tutorial for the Paging library from codelab and I succeeded without any problem.
Now I'm facing some problems in how to handle other data than matches
{
"status": {
"code": 200,
"message": "Matches found"
},
"data": {
"filters": {
"sortable_actions": [
{
"name": "asd",
"value": "sd",
"is_selected_filter": false
},
{
"name": "asd",
"value": "asd",
"is_selected_filter": false
}
],
"filter_actions": [
{
"name": "sdaf",
"display_name": "dafs",
"is_selected_filter": false
}
]
},
"cities": [
"Akora, Japan",
"Zurich, Switzerland"
],
"matches_count": {
"hot": 0,
"warm": 0,
"cool": 17
},
"matches": [
{
"id": "52832",
"type": "asdf",
"attributes": {
"name": "afd",
"pitch": "dsf",
"logo": "adsf",
"plan": "fd",
"country": "sdf",
"city": "faas",
}
},
{
"id": "52832",
"type": "asdf",
"attributes": {
"name": "",
"pitch": "",
"logo": "",
"plan": "",
"country": "",
"city": "",
}
},
{
"id": "52832",
"type": "",
"attributes": {
"name": "",
"pitch": "",
"logo": "",
"plan": "",
"country": "",
"city": "",
}
},
{
"id": "52832",
"type": "",
"attributes": {
"name": "",
"pitch": "",
"logo": "",
"plan": "",
"country": "",
"city": "",
}
}
]
}
}
can you please help me how to get filter and sorting data in my UI.

Dynamic JSON parsing

I am a newbie to android. I am stuck at JSON parsing.
Following is my JSON, in this, the type of menu categories will be dynamic, and I want to arrange this JSON in sectioned recycler view.
Please help me out.
This is my JSON
{
"menu_items": {
"Plat": [{
"menu_name": "jambon à l'os",
"menu_cost": "18.00",
"menu_count": "1",
"category": "Plat",
"menu_tax": "5.50",
"code": "€"
},
{
"menu_name": "tacos",
"menu_cost": "6.00",
"menu_count": "1",
"category": "Plat",
"menu_tax": "5.50",
"code": "€"
}
],
"Entrée": [{
"menu_name": "avocat",
"menu_cost": "7.50",
"menu_count": "1",
"category": "Entrée",
"menu_tax": "5.50",
"code": "€"
}]
},
"order_data": {
"order_id": "278",
"order_number": "REF-5d5e6b86",
"created_at": "1566468998",
"instructions": "",
"fullname": "Rohan Chitnis",
"phonenumber": "7610771871",
"useraddress": "Brest, France",
"image_path": "https://restau-at-home.bzh/uploads/attachments/Jellyfish_2019_08_21_10_49_21.jpg",
"wp": "pune",
"code": "€",
"promocode": null,
"promo_value": null,
"promo_type": null
},
"order_details": {
"total_items": "3",
"order_total": "31.50"
},
"promo_applied": "0",
"error": {
"code": "13",
"status": "200",
"message": "Ok"
}
}
Check this out. Create a generic response class. Extend your classes from that class. To do this properly you can look at Java Generics and Inheritance topics if you are using Java. And then search about Sectioned RecyclerView in Android. Here is a library for this.

Json Data Filteration according to category

I want to know how to filter data. I got data with category name but cannot filter category wise.Here is my data:
{
"TITLE": "tea",
"PRICE": "17",
"QTY": "1",
"CAT_ID": "33",
"CAT_NAME": "POPULAR PRODUCTS",
"TYPE": "veg"
},
{
"TITLE": "Coffee",
"PRICE": "102",
"QTY": "1 ",
"CAT_ID": "8",
"CAT_NAME": "MORNING SPECIAL",
"TYPE": "veg"
},
{
"TITLE": "Jeera chachh",
"PRICE": "42",
"QTY": "1",
"CAT_ID": "33",
"CAT_NAME": "POPULAR PRODUCTS",
"TYPE": "veg"
},
{
"TITLE": "Roti Ghee Wali",
"PRICE": "21",
"QTY": "1",
"CAT_ID": "33",
"CAT_NAME": "POPULAR PRODUCTS",
"TYPE": "veg"
},
{
"TITLE": "Paneer paratha",
"PRICE": "102",
"QTY": "1 ",
"CAT_ID": "8",
"CAT_NAME": "MORNING SPECIAL",
"TYPE": "veg"
},
{
"TITLE": "Mix paratha",
"PRICE": "102",
"QTY": "1",
"CAT_ID": "8",
"CAT_NAME": "MORNING SPECIAL",
"TYPE": "veg"
},
I already parse the data but not able to set in fragment according to category.Can anyone solve my issue.
Step 1: Store the data in database.
Step 2: Search
select * from table where CAT_NAME = 'your_filter_category'.
or better ....CAT_NAME like %your_filter_category%.
In Case of no database;
Store the Data in list.
HashMap<String, ArrayList<Item>> map = new HashMap<>();
ArrayList<Item> itemList = new ArrayList<>();
Loop on List{
Item item = fromLoop index;
if(map.contains(item.getCat())){
itemList = map.get(item.getCat());
itemList.put(item);
map.put(item.getCat(),itemList);
}else{
itemList.clear();
itemList.put(item);
map.put(item.getCat(),itemList);
}
}
//after loop you will get HashMap with keys as categories and Values as the list of selected key category.
Step 3: Publish the results.
Note: No one will do your homework here. the only thing we can do for you, we can assist you how to do.
enter your code to: JSON Formatter and you will see that something is invalid in your JSON, it has multiple root elements. Maybe you should store whole code in JSONArray like this: `
{
"features":
[{
"TITLE": "tea",
"PRICE": "17",
"QTY": "1",
"CAT_ID":"33",
"CAT_NAME": "POPULAR PRODUCTS",
"TYPE": "veg" },
{
"TITLE":"Coffee",
"PRICE": "102",
"QTY": "1 ",
"CAT_ID": "8",
"CAT_NAME":"MORNING SPECIAL",
"TYPE": "veg"
}]
}

Categories

Resources