Send a Json which is like key:{key:value,key:[]} with Volley - android

I am new to using Volley and parsing complex Json.
I have Json like:
"timings": {
"summary": "Mon-Fri 9am-6pm",
"detail": [
"Mon 9am-6pm",
"Tue 9am-6pm",
"Wed 9am-6pm",
"Thu 9am-6pm",
"Fri 9am-6pm"
]
}
I am not sure how to send it. I have tried to search for solutions but no luck.
Some help will be really helpful.

I suggest to use Gson library.
And with Gson create class with name of Timings and contain 2 variables .
data class Timings ( val summery: String , val details : List<String>)
val gson: Gson()
time = gson.fromJson(jsonString,Timings::class.java)
Other way is use Json Object and json array to parse it manually

Related

kotlin, android, json serialization

i'm using google gson converter to serialize an json response from an api call into an kotlin object,
one of the json field is a json object
so this didn'T work:
#Expose
#SerializedName("properties")
val properties: List<ThingProperty>,
i got the following error:
Api call failed: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1
but this work fine:
#Expose
#SerializedName("properties")
val properties: JsonObject,
but i then received a JsonObject and not a list of "second level" kotlin object
So the question is, using serialization or something like that,
how can i just received the original json and convert it properly, for this field, into a list of object based on the jsonObject
note, i received my data using retrofit2
Edit:
there is a json example for this item:
"properties":{
"ActiveEvent":{
"name":"ActiveEvent",
"value":false,
"visible":true,
"title":"Active Event",
"type":"boolean",
"#type":"BooleanProperty",
"readOnly":true,
"links":[{
"rel":"property",
"href":"/things/hydroqc-Maison/properties/ActiveEvent"
}]
},
"PreHeatEvent":{
"name":"PreHeatEvent",
"value":false,
"visible":true,
"title":"Pre-Heat Event",
"type":"boolean",
"#type":"BooleanProperty",
"readOnly":true,
"links":[{
"rel":"property",
"href":"/things/hydroqc-Maison/properties/PreHeatEvent"
}]
},
"PostHeatEvent":{
"name":"PostHeatEvent",
"value":false,
"visible":true,
"title":"Post-Heat Event",
"type":"boolean",
"#type":"BooleanProperty",
"readOnly":true,
"links":[{
"rel":"property",
"href":"/things/hydroqc-Maison/properties/PostHeatEvent"
}]
},
"NextEvent":{
"name":"NextEvent",
"value":null,
"visible":true,
"title":"Next Event",
"type":"string",
"readOnly":true,
"links":[{
"rel":"property",
"href":"/things/hydroqc-Maison/properties/NextEvent"
}]
},

How can I take array out of double quotes

Suppose if I've a string as
"[{"key1": value1}, {"key2": value2}, and so on...]"
is there a way to convert it into array:
[{"key1": value1}, {"key2": value2}, and so on...]
Actually I've to post a JSON request in my android app which should be in the following format:
{
"user_id": "5665",
"restaurant_id": "5",
"total_cost": "660",
"food":[
{"food_item_id": "50"},
{"food_item_id": "51"}
]
}
As in the above code, I've to use the array for food key which is stuck in string which I get using the following code:
val gson = Gson()
val menuIds = gson.toJson(listOfMenuIds)
You can create a dataclass for food_items to represent a item in the "food" array.
Then create another dataclass which has "user", "restaurant_id", ... so on... as members, including a member var foods: List
Then pass the second class to the Gson converter

Parse JSON Array in Response using Retrofit Android

Parse the below JSON Response using Retrofit.
Thanks in advance.
[
{"borrowerId":6,
"borrowerName":"archanaB",
"loanId":"LN3",
"numbersOfEmisPaid":2,
"profit":300.0,
"disburmentAmount":5000.0,
"emisReceived":1967.0
},
{
"borrowerId":6,
"borrowerName":"archanaB",
"loanId":"LN14",
"numbersOfEmisPaid":1,
"profit":150.0,
"disburmentAmount":5000.0,
"emisReceived":983.0
},{
"borrowerId":2,
"borrowerName":"NarendraB",
"loanId":"LN12",
"numbersOfEmisPaid":6,
"profit":175.0,
"disburmentAmount":35000.0,
"emisReceived":36050.0
},
{
"borrowerId":6,
"borrowerName":"archanaB",
"loanId":"LN4",
"numbersOfEmisPaid":18,
"profit":133.0,
"disburmentAmount":5000.0,
"emisReceived":344.0
},
]
You can use one of the Retrofit2 Converter.Factory -
Gson: How to get the value with GSON / Retrofit? [duplicate]
Jackson: Retrofit and Jackson and parsing JSON
kotlinx-serialization: Kotlin Serialization Converter
Convert json to pojo using this site if Java
http://www.jsonschema2pojo.org/
if using kotlin
https://www.json2kotlin.com/
and use it like that, after implementing you will get Object so no need to parse
#POST(your_api)
fun details(
#QueryName id: Int
):
Observable<yout_model_generated_from_above_link>

Moshi Custom Adapter isn't being called

TL;DR:
My questions are:
1 - How can I make an Adapter for the "timestamp": 1515375392.225 to ZonedDateTime.
2 - How can I register the List<Report> adapter in the moshi object Builder if I need the moshi object to get this adapter, according to the documentation?
My JSON string has the following structure:
[
{
"id": 0,
"location": {
"latitude": -22.967049,
"longitude": -43.19096
},
"timestamp": 1515375392.225
},
{
"id": 0,
"location": {
"latitude": -22.965845,
"longitude": -43.191102
},
"timestamp": 1515375392.225
},
.......
}]
The timestamp is an automatic conversion made by the Jackson JavaTimeModule, it converts a ZonedDateTime to a timestamp String in the form of a decimal number representing the seconds and nanoseconds from an Instant.
In order to parse the JSON timestamp String, I made the following Moshi adapter:
public class ZonedDateTimeAdapter {
#FromJson ZonedDateTime fromJson(String timestamp) {
int decimalIndex = timestamp.indexOf('.');
long seconds = Long.parseLong(timestamp.substring(0, decimalIndex));
long nanoseconds = Long.parseLong(timestamp.substring(decimalIndex));
return Instant.ofEpochSecond(seconds, nanoseconds).atZone(ZoneId.systemDefault());
}
#ToJson String toJson(ZonedDateTime zonedDateTime) {
Instant instant = zonedDateTime.toInstant();
return instant.getEpochSecond() + "." + instant.getNano();
}
}
And then I register this adapter as:
Type type = Types.newParameterizedType(List.class, Report.class);
Moshi moshi = new Moshi.Builder().add(new ZonedDateTimeAdapter()).build();
JsonAdapter<List<Report>> reportAdapter = moshi.adapter(type);
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build();
The problem is, when I call my webservice using Retrofit, I get the following Exception:
com.squareup.moshi.JsonDataException: java.lang.NumberFormatException:
For input string: ".067000000" at $[0].timestamp
(keep in mind the nanoseconds .067000000 here won't be the same as the JSON example that I gave before, since they called the webservice at different times).
I tried to place a breakpoint on my ZonedDateTimeAdapter, but it's never being called. But it's influencing Moshi, because if I remove it from the Moshi.Builder, the error changes to:
Caused by: java.lang.IllegalArgumentException: Cannot serialize
abstract class org.threeten.bp.ZoneId
I also tried to change the ZonedDateTimeAdapter to deal with Double instead of String, but it just changes the error message to:
com.squareup.moshi.JsonDataException: java.lang.NumberFormatException:
For input string: ".515376840747E9" at $[0].timestamp
So, basically, I have a bunch of changing error messages and no idea what am I doing wrong. I followed the Moshi documentation on Custom Adapters and I don't know what else to do.
Your JSON adapter’s #ToJson methods is accepting a String but the timestamp is a number. Either change this to be a number (ie. double) or pass a JsonReader instead of a String and read the number out yourself. In this case you can call reader.nextString().

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