0

I have a model written in Kotlin, where all the fields are non-nullable. how do i set a default value for null JSON fields.

Mohamed Benkedadra
  • 1,964
  • 3
  • 21
  • 48
UsherBaby
  • 11
  • 1
  • 4

1 Answers1

2

Moshi will throw a JsonDataException if a Non-null field in the class is null when parsing the JSON.

You could either change your class to set fields to defaults after the JSON has been parsed as detailed here:

https://github.com/square/moshi/issues/762#issuecomment-471422238

Alternatively you can create your own custom adapter which handles null values. The example below checks whether a JSON value is null and then sets it to an empty string.

Moshi/Kotlin - How to serialize NULL JSON strings into empty strings instead?

alexy
  • 464
  • 5
  • 6