Deserialise JSON with dynamic field - android

I'm loading JSON with a completely dynamic field from an API using Retrofit on Android.
This is an example:
{
"success": true,
"messages": {
"success": [
"SUCCESS_MESSAGE"
],
"error": {
"specific_error": {
…
}
}
},
"session": {
"id": "fj4qewqrewq43fdsa",
"expire": null,
"YII_CSRF_TOKEN": "fda432fdafasd78978fdas"
},
"metadata": {…}
}
The structure of the messages object can change with every request. Sometimes there is the success field and sometimes not. Same goes for the error field. The error field especially can be an array but also an object with several other objects and fields inside.
Does it make sense to deserialise the messages field into different POJOs and if so how would I do that? Would it make more sense to keep the field as a JSON object and get values from the object when they are needed?

Related

kotlinx.serialization - partial deserialization

I have a very large json file within my android app with the following struture:
[
{
"id": 123,
"data": {
...
}
},
{
"id": 456,
"data": {
...
}
},
...
]
Depending on the item selected in the UI, I need to deserialize only the item with the corresponding id, but right now I'm deserializing the whole file and then do the filter, which takes time and memory to just extract the id I need.
Is there a way to deserialize only the section I need?
I'm using kotlinx.serialization.

How To Parse Response of Multiple Types of Single Key

How To Parse Response of Multiple Types?
Key is like (suppose student_list is a key of list types when student_list is empty then it makes as a string like student_list=""), How to manage this types of response using Retrofit? I am using MVVM Model with retrofit.
My Response:
when I get Data into the List
{
"status": 200,
"data": [
{
"prod_month_total": 2989.61,
"product": "GAS"
},
{
"prod_month_total": 39566.22,
"product": "OIL"
},
{
"prod_month_total": 83912.55,
"product": "OTHER"
}
]
}
when List is Empty Then Response:
{"status":404,"data":"No result found"}
I am getting this Error:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 23 path $.data
first create the right model calss use this site http://www.jsonschema2pojo.org
than use
`if( reponce.isSucessful){
if(responce.status==200){
//code here
}
else{
// find the error
}
}else
{
//
}`

Json parsing using Gson and Retrofit (Custom Deserializer)

I need to build list of places (from response array create instance of place and finally receive list of places (place in json))?
How to parse it using Gson and Retrofit with custom deserializer?
I have following strucutre:
{
"success": true,
"error": null,
"response": [
{
"loc": {
"lat": 51.50853,
"long": -0.12574
},
"place": {
"name": "London",
"state": "",
"stateFull": "",
"country": "GB",
"countryFull": "United Kingdom",
"region": "",
"regionFull": "",
"continent": "eu",
"continentFull": "Europe"
},
"profile": {
"elevM": 21,
"elevFT": 69,
"pop": 7556900,
"tz": "Europe/London",
"tzname": "BST",
"tzoffset": 3600,
"isDST": true,
"wxzone": null,
"firezone": null,
"fips": null,
"countyid": null
}
},
.............
.............
]
}
You can use Android Studio plugin RoboPOJOGenerator. It is very easy to make model classes from data.
This answer tells how to handle List response in retrofit.
Update
I don't think it is good idea to make custom deserializer just to parse a list. When you can filter or map list after getting response. It will take upto 3-4 lines of code.
If you don't want many classes. then you can safely delete Profile.java and Loc.java in your case, Gson will parse only data that you have declared in your pojo.
Make generic response class
You can make single class for handling all response by using Java Generics. See example.
public class ApiResponse<T> {
#SerializedName("error")
#Expose
private String error;
#SerializedName("success")
#Expose
private boolean success;
#SerializedName("response")
#Expose
private T response;
// make getter setters
}
Now in ApiService you can define response type. Like this
#GET("api/users/login")
Call<ApiResponse<ModelUser>> getUser();
#GET("api/users/login")
Call<ApiResponse<ModelCity>> getCity();
Thus you don't have to create 3 classes every time. This generic class will do work for all response.

Cached complex/nested objects and querying them with Greendao Android

Ok this is the scenario, I have a complex object like this (see below) and it is downloaded and parsed using Retrofit. I generated the Java class (POJO) using GreenDao and everything is ok while the app is running: retrofit response body is as I want, I insert this response.body() to the DB and if I query in other activity this object is retrived by GreenDao with all the attributes setted (is the cached object).
The problem is when I clear all the caches or close the app and open it again, the list of the nested objects is null (see the second json below).
How can I solve this? Thanks in Advance
Json sent from the server
{
"id" : 91
"timestamp": 1487786669,
"groups": [
{
"id": "G1",
"name": "Some name",
"nextPaymentDate": "2017-06-01",
"totalAmount": 1000.00,
"overdraft": false,
"apoyaT": true
},
{
"id": "G2",
"name": "Other name",
"nextPaymentDate": "2017-06-02",
"totalAmount": 1000.00,
"overdraft": true,
"apoyaT": false
}
]
}
Json/JavaObject when the cache is cleared
{
"id": 91
"timestamp": 1487786669,
"groups": null
}
My GreenDao Generator
/* List Entity ***************************/
Entity list = schema.addEntity("List_p");
list.addIntProperty("id").primaryKey();
list.addLongProperty("timestamp");
/* Group Entity **************************/
Entity group = schema.addEntity("Group");
group.addStringProperty("id").primaryKey();
group.addStringProperty("name");
group.addStringProperty("nextPaymentDate");
group.addDoubleProperty("totalAmount");
group.addBooleanProperty("overdraft");
group.addBooleanProperty("apoyaT");
Property listId = group.addLongProperty("listId").getProperty();
list.addToMany(group, listId, "groups");

How to generate GSONFormat for a property that can either be an object or string?

I'm using GSON for parsing response from a Volley request and got stuck in creating a GSON format when the response has a property that can either be a string or an object or an array perhaps... e.g content
{
"data": {
"date_updated": "2016-12-21T03:55:29.955Z",
"date_created": "2016-12-21T03:55:29.955Z",
"content": "String here",
"content": {
"longitude": "",
"latitude": ""
},
"status": "PROC",
"_id": "5859fd31a93c7235575d62db"
}
}
My current process in creating a GSON model is:
Create a java class
Right click and select Generate > GSONFormat
Paste the object I'm trying to convert then use it in Volley.
I tried the above object but it doesn't proceed. I think it's because of same property name.
Thanks for your advice.
You can use GsonFormat, you can look this:
https://github.com/zzz40500/GsonFormat

Categories

Resources