https://kotlinlang.org logo
Title
m

mathew

02/08/2018, 6:48 AM
I have a string which holds a json response. How Can I convert or cast it into JsonObject in Kotlin? var string : String = "{\n" + " \"success\": true,\n" + " \"response\": {\n" + " \"message\": \"Login is valid.\"\n" + " }\n" + "}"
d

dave08

02/08/2018, 7:00 AM
#klaxon library or #kotson?
e

edwardwongtl

02/08/2018, 7:03 AM
Just the same way as you do in Java
d

david.bilik

02/08/2018, 7:06 AM
btw, if you use triple quotes, you dont have to put that escaping everywhere
val breakerEnabled = """
        {
          "CmdEnabled": "true",
          "CurrState": "Closed"
        }
    """
m

mathew

02/08/2018, 7:10 AM
Thanks guys, I got it. Same as java var jsonObj = JSONObject("{\n" + " \"success\": true,\n" + " \"response\": {\n" + " \"message\": \"Login is valid.\"\n" + " }\n" + "}")
d

dave08

02/08/2018, 8:10 AM
I use #klaxon to get json into data classes for api contracts, I had tried the Java version of Gson, but I ended up with nulls in non-null vars... its easier to work with data classes than JsonObject when the structure is known, at also acts like an extra check that you're really getting what you're expecting... Klaxon even works well with sealed classes, so various response formats can be modeled and validated very simply...
l

lex

02/08/2018, 10:01 AM
try #jackson-kotlin, it is mature and have kotlin support module