1

I need help to convert String in JSON object.

This is the response I am getting from WebView

 webView.evaluateJavascript(
                    "document.getElementById('formio-submitted-data').textContent"
            ) { value ->

The response is

  value = ""{\"data\":{\"plantName\":\"Bhanu\",\"address\":\"Abcd\",\"totalCapacity\":25},\"isValid\":true}""

The response I have got is in a string. I have to convert it into JSON. How can I achieve this?

9
  • Does this help bezkoder.com/kotlin-parse-json-gson? Commented Aug 5, 2021 at 5:39
  • My JSON contain \ I have to convert value into a JSON object and forward it. I Don't know how to achieve it. Commented Aug 5, 2021 at 5:43
  • Can you provide actual example that has `\`? Commented Aug 5, 2021 at 5:46
  • It is like this . ""{\"data\":{\"FIRSTFIELD\":\"1\",\"FIRSTFIELD2\":\"2}"" This is the JSON I AM GETTING Commented Aug 5, 2021 at 5:49
  • may be replace \" with just single quote and then try to use the same function Commented Aug 5, 2021 at 5:53

2 Answers 2

2

Try this

val jsonParser = JsonParser()
val jsonObject = jsonParser.parse("your jsonString with backslash").asJsonObject
Sign up to request clarification or add additional context in comments.

4 Comments

I was doing this before val resp: JsonObject = JsonParser().parse(value).asJsonObject val jsonObject = JsonObject() . but my app crashes and it is giving me error A/chromium: [FATAL:jni_android.cc(249)] Please include Java exception stack in crash report A/libc: Fatal signal 5 (SIGTRAP), code -6 (SI_TKILL) in tid 4443
Just to narrow down the problem, can you please try without \. I mean manually remove them and see if you still get this error. Just to find out this exception is because of \
I am trying to remove \ manually but this value.replace("//","") is not working. Or I should Iterate one by one. Kotlin does not have replaceAll function
Deprecated. Use static function instead - val jsonObject = JsonParser.parseString("your jsonString with backslash")
0

I have got the solution.

The problem was in my script in webview.

What I did was

doneButton.setOnClickListener{
            var view=it
            webView.evaluateJavascript(
                    "JSON.parse(document.getElementById('formio-submitted-data').textContent)"
            ) { value ->
                if(value.length!=2){

                    val resp: JsonObject = JsonParser().parse(value).asJsonObject
                    val jsonObject = JsonObject()
                    jsonObject.add("data", resp)

I have changed the code inside evaluateJavaScript.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.