kamikat / moshi-jsonapi

JSON API v1.0 Specification in Moshi.
MIT License
156 stars 35 forks source link

how do I send a null field to the server? #117

Open KotlinWay opened 2 years ago

KotlinWay commented 2 years ago

How do I put null in the network model field? I have a model like this

@JsonApi(type = "notes") data class Note( var name: String? = null, var description: String? = null, var note: String? = null, @field:Json(name = "created-at") var createdAt: Date? = null }

I want to patch the null value in the createdAt field to the server, but this field is ignored and it simply does not exist in the body. {"data":{"type":"notes","id":"168356"}} How can I send null?

kamikat commented 2 years ago

Use serializeNulls call on a JsonAdapter object may help:

moshi.adapter(Document.class).serializeNulls().toJson(document)

For more adapter options: https://github.com/square/moshi#adapter-convenience-methods

5treetArt commented 2 years ago

@kamikat, .serializeNulls() method is useless in this case because of skipping null fields in ResourceAdapter.writeFields. Of course this skip can be avoided by setting writer.setSerializeNulls(true), but in this case all the null fields of this object will be written into JSON. Which is not the goal, because we want to write only one specific field as null. It will be good to have something like @SerializeNulls annotation for the field.

antaki93 commented 1 year ago

There is a custom solution on the StackOverflow: https://stackoverflow.com/a/52265735/7918717