0

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Bhanu Nautiyal
  • 1
  • 1
  • 1
  • 4

2 Answers2

1

Try this

val jsonParser = JsonParser()
val jsonObject = jsonParser.parse("your jsonString with backslash").asJsonObject
Bharat
  • 1,192
  • 7
  • 14
  • 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 – Bhanu Nautiyal Aug 05 '21 at 06:41
  • 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 \ – Bharat Aug 05 '21 at 06:45
  • 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 – Bhanu Nautiyal Aug 05 '21 at 07:04
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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Bhanu Nautiyal
  • 1
  • 1
  • 1
  • 4