Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moshi ignore field in Kotlin

I want to know how to ignore a Kotlin class field when using Moshi.

I've found this answer for Java (Moshi ignore field), that indicates to use the keyword transient as follows

private transient String your_variable_name;

But I can't find the right way to get this done in Kotlin.

like image 481
heisen Avatar asked Nov 18 '17 16:11

heisen


3 Answers

Use the @Transient annotation.

@Transient
private val your_variable_name: String

Doc here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-transient/index.html

like image 97
marstran Avatar answered Nov 19 '22 10:11

marstran


Kotlin + Retrofit + Moshi

In case where you want to conditionally ignore fields, you can set it to null.

data class  User(var id: String,  var name: string?)

val user = User()
user.id = "some id"
user.name = null

The Json generated would be

user{
"id": "some id"
}
like image 29
MetaPlanet Avatar answered Nov 19 '22 12:11

MetaPlanet


Here is another way

@field:Json(ignore = true)
val your_variable_name: String
like image 1
Ji Fang Avatar answered Nov 19 '22 12:11

Ji Fang