Hi, what's the best practice for returning an arbi...
# http4k
a
Hi, what's the best practice for returning an arbitrary Map object as a JSON Response? No validation, as the keys will vary often. The 3 examples at https://www.http4k.org/guide/modules/json/ all describe objects specifically created to be JSON, not a normal Map (or list of Pairs). And can http4k automatically set the Response's content type to
application/json
? Perhaps an equivalent of Flask's
jsonify
(https://flask.palletsprojects.com/en/1.1.x/api/#flask.json.jsonify). Thanks.
d
these both work depending on if you want to use lenses or not:
Copy code
fun main() {
    val m = mapOf("too" to "bwob")
    println(Request(Method.GET, "").with(Body.auto<Map<String, Any>>().toLens() of m))
    println(Jackson.asJsonObject(m))
}
a
great, thanks, I was using the 2nd option, wasn't sure if that was considered best practice. Am I correct that only Jackson has
asJsonObject
, not Kotlinx or Moshi? And setting
application/json
must be done manually?
d
anything that actually has a Json object API model will have that method. Moshi for example doesn't although it does the marshalling. Check out
Json
vs
AutoMarshallingJson
vs
JsonLibAutoMarshallingJson
KotlinX has a
JsonElement
class so does have that method
If you want the content type to be set automatically then you'll need a lens - which means you'll need an implementation of
AutoMarshallingJson
a
I don't mind setting Content-Type -- just want to be sure I am using Http4k efficiently
d
My default is just to use Jackson with an auto lens.
Then if you ever want to switch you can just switch out the Json implementation library and replace the imports
(although TBH you probably wouldn't want to be Jackson is the one that plays best IMHO)
a
good to know, I started using moshi but had converted almost all my serialization to kotlinx
Thanks for the quick replies. Started working on my project again recently during lockdown. Have a couple of edge cases and scenarios, hope it's ok if I ask them on Slack
d
of course! 🙂