https://kotlinlang.org logo
#http4k
Title
# http4k
g

Gopal S Akshintala

04/05/2022, 4:19 PM
Hi, request some help on this ☝🏼
d

dave

04/05/2022, 4:46 PM
I think the basic problem here is that until you see the JSON you can't tell what the class is - so you need to be able to discriminate somehow Moshi will require a custom adapter for this to make it work - and this will require you to implement your own Configurable Moshi instance
You can copy the Moshi class from http4k and add a custom adapter
For writing that you will need to look at the Moshi docs
But once it's configured you can use lenses as normal because the "mapper" inside your custom Moshi will be configured correctly for this case
g

Gopal S Akshintala

04/06/2022, 2:34 AM
Thanks @dave that makes sense… I think for now I will settle with
val pokemon = Moshi.asA(result.bodyString(), clazz.kotlin)
and incrementally build upon it
d

dave

02/09/2023, 8:34 AM
The reason is that we try to have an identical contract across all of the implementations. If you want to call asA with a type manually (and would be interested to know the exact use-case), an easy way would be to just extract your inner moshi configuration. It's a little wordy, but this will work to ensure you have the same configuration across everything
Copy code
private val myInnerMoshiB = Moshi.Builder()
    .addLast(EventAdapter)
    .addLast(ThrowableAdapter)
    .addLast(ListAdapter)
    .addLast(MapAdapter)
    .asConfigurable()
    .withStandardMappings()
    .done()

private val myInnerMoshi = myInnerMoshiB.build()

object MyMoshi : ConfigurableMoshi(myInnerMoshiB)

fun <T> MyMoshi.asA(input: String, type: Type): T = myInnerMoshi.adapter<T>(type).fromJson(input)!!
g

Gopal S Akshintala

02/09/2023, 9:14 AM
Thanks @dave I did exactly that 🙂, but sort of feels like a Hack. So wanted to check if this can be contributed to the library.
d

dave

02/09/2023, 9:16 AM
What exactly was the use case that you needed it for BTW?
g

Gopal S Akshintala

02/09/2023, 9:23 AM
So I am building a tool (similar to Postman on JVM) and the tool is supposed to take moshi adapters as parameters from the caller. I am using Http4k for request response and unmarshalling, but I need a customized moshi with these extra custom adapters added. It’s a small code-base you may review this line: revoman-root/ReVoman.kt