不使用正则表达式将字符串转换为地图

Convert String to Map without regex

我有一个服务器 returns 这种格式的字符串:

{"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}`

然后我通过这样做提取 data

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

最后我得到了这个字符串:

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

有没有一种有效的方法可以将值提取到 HashMap 中,键位于“:”左侧,值位于“:”右侧?

我已经在这里看到了答案 (Convert String to Map) 但我不允许使用正则表达式

问题是您通过显式写入类型

强制您的 jsonObj 成为 Any
val jsonObj : Any!

因为你的方法实际上 returns 字符串(因为它以 toString() 结尾)

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

随便写

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

然后使用我们在评论中提出的答案中的解决方案。

val result: Map<String, Any> =
   ObjectMapper().readValue(jsonObjStr, HashMap::class.java);