ansman/kotshi

Json Default Value to Lists?

ademar111190 opened this issue · 12 comments

Hi guys, what about an annotation to give default values to lists?
Something like:

@Target(AnnotationTarget.VALUE_PARAMETER,
        AnnotationTarget.FUNCTION,
        AnnotationTarget.CONSTRUCTOR,
        AnnotationTarget.FIELD,
        AnnotationTarget.PROPERTY_GETTER)
@Retention(AnnotationRetention.SOURCE)
@JsonDefaultValue
annotation class JsonDefaultValueList

@JsonDefaultValueList
fun <T> defaultJsonDefaultValueList() = listOf<T>()

I don’t really understand this issue, what you describe is already supported, in exactly the same way as in your example

Sorry I was not clear.
What I was trying to say is why do not add this feature to the library, in the same way as the library already does with the defaultString and others.
Currently, everyone needs to add this same code to its project, so it is the motivation.

I see your point, I need to think about this. One would probably want to name it JsonDefaultValueEmptyList and then we need to add the same for sets and maps.

Sure.
I think the class can be more similar to the others and receive a value.

Annotation values must be compile time constants so lists are no allowed, otherwise we could simply create a generic annotation that accepts default values for all types.

I got it.
Given the limitation, I would say the idea to have the empties list, set, map, etc is good.

@JakeWharton It wouldn't work doing it in Moshi if you want a default value when the key is absent from the json.

If a key is absent from the Json the adapter for that field is never queried.

For example given this class:

public class Foo {
  public Bar bar;
}

and this json:

{}

the adapter for Bar would never be called.

Closing this, it's no longer relevant when #108 is merged