When JSON data comes null, then I want, it should take the default value and I do not have to null check in the Moshi Converter always.
I am using the Moshi-kotlin
as well, but still, the result
are the same.
{
"image": null,
"visible": null
"name": null,
"description": null
"id": null,
"subcategories": null
"ordinal": null,
"isEvent": null,
"style": null
}
Here is my Data class
where I am keeping its default value
.
Make the data class entries non-nullable (remove the ?)
Then put in every place that you invoke the constructor, ?: ""
. Anything that is null will be changed to an empty string
Alternatively, you could create a .invoke(...) method on the companion object and use this to process the values.
Consider defining two model classes:
You can follow the EventJson example from the Moshi readme to pretty easily convert between these when you decode the server object.
class EventJsonAdapter {
@FromJson Event eventFromJson(EventJson eventJson) {
Event event = new Event();
event.title = eventJson.title;
event.beginDateAndTime = eventJson.begin_date + " " + eventJson.begin_time;
return event;
}
@ToJson EventJson eventToJson(Event event) {
EventJson json = new EventJson();
json.title = event.title;
json.begin_date = event.beginDateAndTime.substring(0, 8);
json.begin_time = event.beginDateAndTime.substring(9, 14);
return json;
}
}
Trying to use the same object for business logic and JSON is awkward. Having different objects for each is a simple way to avoid that. Plus you can be deliberate about what happens when sending these default values back to the server.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.