29

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.

kaya3
  • 47,440
  • 4
  • 68
  • 97
heisen
  • 1,067
  • 3
  • 9
  • 25

3 Answers3

56

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

marstran
  • 26,413
  • 5
  • 61
  • 67
3

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"
}
MetaPlanet
  • 129
  • 4
1

Here is another way

@field:Json(ignore = true)
val your_variable_name: String
Ji Fang
  • 3,288
  • 1
  • 21
  • 18
  • 1
    Does not seem to have the `ignore` param for Json – T D Nguyen Apr 01 '22 at 06:42
  • It was added recently. Try updating your Moshi version – Ji Fang Apr 01 '22 at 16:19
  • I am pretty sure about this. [Moshi Json Documentation](https://square.github.io/moshi/1.x/moshi/moshi/com.squareup.moshi/-json/index.html) – T D Nguyen Apr 02 '22 at 02:25
  • Not sure about the doc. But here is the [source](https://github.com/square/moshi/blob/master/moshi/src/main/java/com/squareup/moshi/Json.kt) – Ji Fang Apr 04 '22 at 23:16
  • it was added to master but is not yet in a release. The [github readme](https://github.com/square/moshi) is misleading in the sense that you're viewing the docs for master unless you specifically switch to [a release branch](https://github.com/square/moshi/tree/moshi-parent-1.13.0) – Roger Jun 22 '22 at 16:05