Thomas Cirksena
Thomas Cirksena

Reputation: 947

How to serialize a value class with moshi so it just return it's value

I hava a value classin my android project (kotlin) and I want to parse a object, that contains this value class as type for a attribute, to json.

Let's say this is my value class:

@JsonClass(generateAdapter = true)
@JvmInline
value class CustomDate(val value: String)

and this is my object that contains a attribute with the value class shown before:

data class MyTestClass(
    val attr1: CustomDate
)

If I now try to convert it to Json using moshi I will get this:

...
attr1: {
   value: "a test valu"
}
...

What I want it to transform the object to this:

...
attr1: "a test valu"
...

but I don't know how to achieve this. There is no JsonTransformingSerializer for moshi like it seems so how am I able to transform the object itself and not only the value like done using a JsonAdapter?

Maybe I missed something but I would appriciate any suggestion.

Upvotes: 0

Views: 1759

Answers (1)

Thomas Cirksena
Thomas Cirksena

Reputation: 947

I found how how to use it in case anyone is facing the same problem:

I needed to create a custom JsonAdapter.Factory and a according JsonAdapter<CustomDate>:

class CustomDateAdapterFactory : JsonAdapter.Factory {
  override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? {
    if (!annotations.isEmpty()) return null
    if (type === CustomDate::class.java) return CustomDateAdapter()
    return null
  }
}

class CustomDateAdapter : JsonAdapter<CustomDate>() {
  @FromJson
  override fun fromJson(reader: JsonReader): CustomDate {
    return CustomDate(reader.nextString())
  }

  @ToJson
  override fun toJson(writer: JsonWriter, value: CustomDate?) {
    writer.value(value?.value)
  }
}

After that I had to add the CustomDateAdapterFactory to my moshi builder:

Moshi.Builder()
  .addLast(CustomDateAdapterFactory())
  .build()
 

That's it! :)

Upvotes: 4

Related Questions