Moshi: @Json does not work whereas changing property name works

Created on 22 Feb 2018  路  2Comments  路  Source: square/moshi

Hey there, I am not able to parse my Json with Moshi when I define @Json(name).
Is it an expected behavior?

The way Moshi is implemented

val moshi = Moshi.Builder().build()
val jsonAdapter = moshi.adapter<Route>(Route::class.java)
val route = jsonAdapter.fromJson(it)

The Json

{
   "sourceLocation": [
        -73.9654327,
        40.7794406
   ]
}

Parameter is not null after parsing

data class Route(
    var sourceLocation: List<Double>
)

Parameter is null after parsing

import com.squareup.moshi.Json

data class Route(
    @Json(name = "sourceLocation")
    var originLocation: List<Double>
)

Most helpful comment

You need to target the annotation with @field:Json.

fun main(vararg args: String) {
  val moshi = Moshi.Builder().build()
  val adapter = moshi.adapter<Route>(Route::class.java)
  val actual = adapter.fromJson("""
    {
      "sourceLocation": [
        -73.9654327,
        40.7794406
      ]
    }
    """.trimIndent())
  println(actual)
}

data class Route(
    @field:Json(name = "sourceLocation")
    var originLocation: List<Double>
)
Route(originLocation=[-73.9654327, 40.7794406])

All 2 comments

You need to target the annotation with @field:Json.

fun main(vararg args: String) {
  val moshi = Moshi.Builder().build()
  val adapter = moshi.adapter<Route>(Route::class.java)
  val actual = adapter.fromJson("""
    {
      "sourceLocation": [
        -73.9654327,
        40.7794406
      ]
    }
    """.trimIndent())
  println(actual)
}

data class Route(
    @field:Json(name = "sourceLocation")
    var originLocation: List<Double>
)
Route(originLocation=[-73.9654327, 40.7794406])

Or add the KotlinJsonAdapterFactory from the Kotlin artifact to your Moshi.Builder.

Was this page helpful?
0 / 5 - 0 ratings