Mario Burga
Mario Burga

Reputation: 1157

How to use the class data of a json element that have colon in name - Kotlin

I have the following Json:

_embedded: {
  wp:featuredmedia: [
    {
      id: 9060,
      date: "2018-05-28T17:41:21",
      author: 2,
      caption: {
        rendered: ""
      },
      source_url: "h.t.t.p.s://mydomain_com/myimage.jpg",
    }
  ]
}

I am using httpOk and Gson to deserialize, I have the following data classes.

data class Embedded(
    val wp:featuredmedia: List<Wpfeaturedmedia>
)

data class Wpfeaturedmedia(
    val source_url: String
)

Everything works correctly, but my problem is when it comes to obtaining the image of source_url, because the name wp:featuredmedia has two points (colon). How do I make the class work correctly? Image with the error

UPDATE: WORK NOW WITH

data class Embedded(
        @SerializedName("wp:featuredmedia") val wpfeaturedmedia: List<Wpfeaturedmedia>
)

Upvotes: 2

Views: 498

Answers (2)

Vasilii Kovalev
Vasilii Kovalev

Reputation: 11

you may use @JsonProperty

data class ResponseData(
   @JsonProperty("wp:featuredmedia")
   val wpfeaturedmedia: List<SubData>
) { data class SubData(...)}

Upvotes: 1

Konrad Botor
Konrad Botor

Reputation: 5063

It's simple - name your field wpfeaturedmedia (without the colon) and it will be mapped correctly.

Edit: It seems I was wrong - Gson simply skips wp:featuredmedia during deserialization unless field wpfeaturedmedia is annotated with @SerializedName("wp:featuredmedia")

Upvotes: 1

Related Questions