Last active
August 15, 2021 19:13
-
-
Save dangets/409569d93fb4ca56d1c2a48e6d972394 to your computer and use it in GitHub Desktop.
kotlin moshi adapters demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dangets | |
import com.squareup.moshi.FromJson | |
import com.squareup.moshi.JsonClass | |
import com.squareup.moshi.Moshi | |
import com.squareup.moshi.ToJson | |
import java.time.LocalDate | |
import java.util.* | |
data class Partition(val type: Type, val id: Int) { | |
enum class Type { ACCOUNT, CLIENT } | |
companion object { | |
fun account(id: Int) = Partition(Type.ACCOUNT, id) | |
fun client(id: Int) = Partition(Type.CLIENT, id) | |
} | |
} | |
@JsonClass(generateAdapter = true) | |
data class SecurityMatchRequest( | |
val requestId: UUID = UUID.randomUUID(), | |
val partition: Partition, | |
val alternateId: String?, | |
val cusip: String?, | |
val isin: String?, | |
val sedol: String?, | |
val maturityDate: LocalDate?, | |
val proposedSecurityId: Int?) | |
class UuidJsonAdapter { | |
@ToJson fun toJson(value: UUID?) = value?.toString() | |
@FromJson fun fromJson(input: String) = UUID.fromString(input) | |
} | |
class LocalDateJsonAdapter { | |
@ToJson fun toJson(value: LocalDate?) = value?.toString() | |
@FromJson fun fromJson(input: String) = LocalDate.parse(input) | |
} | |
fun main(args: Array<String>) { | |
val smr = SecurityMatchRequest( | |
partition = Partition.account(231), | |
alternateId = "ALT-ID", | |
cusip = null, | |
isin = null, | |
sedol = "some-sedol", | |
//maturityDate = LocalDate.parse("2018-10-12"), | |
maturityDate = null, | |
proposedSecurityId = null | |
) | |
val moshi = Moshi.Builder() | |
.add(UuidJsonAdapter()) | |
.add(LocalDateJsonAdapter()) | |
.build() | |
val json = SecurityMatchRequestJsonAdapter(moshi) | |
.toJson(smr) | |
println(smr) | |
println(json) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
works with moshi-kotlin 1.6.0
need to setup kapt for annotation processing