square / moshi

A modern JSON library for Kotlin and Java.
https://square.github.io/moshi/1.x/
Apache License 2.0
9.74k stars 758 forks source link

Access nested values in json object #1633

Closed yzheka closed 1 year ago

yzheka commented 1 year ago

Let's say we have some complex json like this

{
   "city":{
      "name":{
         "full":"London",
         "short":"Lon"
      }
   }
}

Would be grat to have a feature to convert it to

data class City(
   @Json(name="city.name.full")
   val fullName:String="",
   @Json(name="city.name.short")
   val shortName:String=""
)
ZacSweers commented 1 year ago

This doesn't have to be built into Moshi core to be doable. Check out the Wrapped adapter here: https://github.com/serj-lotutovici/moshi-lazy-adapters

yzheka commented 1 year ago

@ZacSweers looks almost like I suggest but not. There we declare the path we want to pick fom response inside Retrofit interface method. But I suggest to parse json into custom class structure. This can improve creating POJO for json like this:

{
   "keyA"{
      "keyB":{
         "keyC":{
            "keyD":"someValue"
         }
      }
   },
  "keyB":"someValue"
}
yzheka commented 1 year ago

with this feature no need to create lots of classes. Just one class where with 2 properties:

data class SomeData(
   @Json("keyA.keyB.keyC.keyD") val keyD:String, // or @Json("keyA.keyB.keyC") because wee already declared val keyD
   @Json("keyB") val keyB:String //works like always
)
ZacSweers commented 1 year ago

The linked Wrapped adapter above does exactly what you're asking for, please read it.

yzheka commented 1 year ago

@ZacSweers sorry, I can't find it in docs. can you point me to it please? I see how it is used with retrofit, but my idea to use it as json parser without retrofit.