hiya - I'm a bit confused on how to use Moshi in a...
# http4k
p
hiya - I'm a bit confused on how to use Moshi in a situation which is not Request or Response related, in my http4k server I'm using Redis's JSON functions and I want to read a JSON value from Redis and parse it from JSON to a class: "Something", e.g.
Copy code
data class Something(@Json(name="foo_bar") val fooBar: String)

object MyMoshi : ConfigurableMoshi(
    com.squareup.moshi.Moshi.Builder().asConfigurable()
                                      .withStandardMappings()
                                      .text(::Something, Something::fooBar)
                                      .done()

)
I do use moshi in other projects, so not sure what I'm meant to do to add an adapter to the http4k wrapper around it, e.g
Copy code
val moshi:   Moshi = Moshi.Builder().build()
val adapter: JsonAdapter<Something> = moshi.adapter(Something::class.java)
something = requireNotNull(adapter.fromJson(json))
d
You don't need to define your own Moshi instance. You should be able to just use Moshi.asFormatString() and Moshi.asA() to convert
☝️ 1
s
You can use your object directly:
Copy code
val something = Something("hello")
    val json = MyMoshi.asFormatString(something)
    println(json)

    val fromJson = MyMoshi.asA(json, Something::class)
    println(fromJson)
p
oh wow, thanks @dave I'll have a go
s
And as @dave pointed out you can just use
org.http4k.format.Moshi
rather than defining your own object
p
cheers, I think I'm on the right track now.
👍 1
j
Nice ray-traced fractal!
m
Bit late, and most of the things were said already. But there's one more thing to make it nicer.
Copy code
val something = Something("hello")
val lens = MyMoshi.asBiDiMapping<Something>()
val json = lens(something)
println(json)

val fromJson = lens(json)
println(fromJson)
And mimics the approach you would use with Request/Response body lenses
http4k 3
p
crikey - thanks.
@James Richardson

https://youtu.be/qbjyTp51VEA?t=456

(fractal is from a classic Amiga demo)
d
That's a computer I haven't seen in a very long time...
💾 1
j
Ah yes I know, "ray-traced fractal" is a quote from it!
👍 1