英文:
Convert String to Map without regex
问题
我有一个返回以下格式字符串的服务器:
{"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中,以:
左边的内容作为键,以:
右边的内容作为值?
我已经在这里看到了答案(https://stackoverflow.com/questions/17691304/convert-string-to-map),但是我不能使用正则表达式。
英文:
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 (https://stackoverflow.com/questions/17691304/convert-string-to-map) but I am not allowed to to use regex
答案1
得分: 0
问题在于您通过显式写入类型将您的 jsonObj
强制转换为 Any
val jsonObj: Any!
由于您的方法实际上返回一个字符串(因为它以 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);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论