-1

I have a server that returns a String of this format:

{"success":true,
 "visible":false,
 "data":
     {"ref":"asfdasfsadfaeweatsagsdfsad",
      "userRef":"asdfsadfsa","accountType":"REAL",balance":43},
"code":"2200",
"msg":null,
"msgRef":null,
"successAndNotNull":true,
"failedOrNull":false,
"failed":false,
"failedAndNull":false}`

Then I extract the data by doing this:

val jsonObj : Any! = JSONObject(serverResponse.toString()).get("data").toString()

and I end up with this String:

"{"ref":"safdasfdwaer",
 "userRef":"fdgsgdsgdsfg",
 "accountType":"REAL",
 "balance":43}"

Is there an efficient way to extract the the values into a HashMap with key what is on the left of ":" and value what is on the right of ":"?

I have already seen the answer here (Convert String to Map) but I am not allowed to to use regex

C96
  • 477
  • 8
  • 33
  • Ive seen this thread. JSONObject(serverResponse.toString()).get("data") in Kotlin returns data type "Any!" which leaves me unable to use new ObjectMapper().readValue(JSON_SOURCE, HashMap.class); because I dont actually have a JSON_SOURCE – C96 Sep 02 '20 at 10:45
  • @JanisLadja convert it to String then. – Steyrix Sep 02 '20 at 10:49
  • And then from String to JSON, or from String to Json to Map? – C96 Sep 02 '20 at 10:50
  • 1
    JSON_SOURCE is of type String, so you will pass your String to new `ObjectMapper().readValue(String, HashMap.class);` and get the map – Steyrix Sep 02 '20 at 10:53
  • @JanisLadja I proposed an answer where described thing in a detailed way – Steyrix Sep 02 '20 at 10:58

1 Answers1

0

The problem is that you force your jsonObj to be Any by writing type explicitly

val jsonObj : Any!

Since your method actually returns String (as it ends with toString())

JSONObject(serverResponse.toString()).get("data").toString()

Just write

val jsonObjStr = JSONObject(serverResponse.toString()).get("data").toString()

And then use solution from the answer we proposed in the comments.

val result: Map<String, Any> =
   ObjectMapper().readValue(jsonObjStr, HashMap::class.java);
Steyrix
  • 2,796
  • 1
  • 9
  • 23
  • Why even go through the hoops of first using `JSONObject`, converting it back to a string, and then using `ObjectMapper`? Just use `ObjectMapper` directly. – Mark Rotteveel Sep 05 '20 at 07:51