将字符串转换为Map,无需使用正则表达式。

huangapple go评论75阅读模式
英文:

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(&quot;data&quot;).toString()

Just write

val jsonObjStr = JSONObject(serverResponse.toString()).get(&quot;data&quot;).toString()

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

val result: Map&lt;String, Any&gt; =
   ObjectMapper().readValue(jsonObjStr, HashMap::class.java);

huangapple
  • 本文由 发表于 2020年9月2日 18:36:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63703767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定