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

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

Convert String to Map without regex

问题

我有一个返回以下格式字符串的服务器:

  1. {"success":true,
  2. "visible":false,
  3. "data":
  4. {"ref":"asfdasfsadfaeweatsagsdfsad",
  5. "userRef":"asdfsadfsa","accountType":"REAL","balance":43},
  6. "code":"2200",
  7. "msg":null,
  8. "msgRef":null,
  9. "successAndNotNull":true,
  10. "failedOrNull":false,
  11. "failed":false,
  12. "failedAndNull":false}

然后,我通过以下方式提取data

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

然后得到以下字符串:

  1. "{"ref":"safdasfdwaer",
  2. "userRef":"fdgsgdsgdsfg",
  3. "accountType":"REAL",
  4. "balance":43}"

有没有一种有效的方法将这些值提取到一个HashMap中,以:左边的内容作为键,以:右边的内容作为值?

我已经在这里看到了答案(https://stackoverflow.com/questions/17691304/convert-string-to-map),但是我不能使用正则表达式。

英文:

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

  1. {"success":true,
  2. "visible":false,
  3. "data":
  4. {"ref":"asfdasfsadfaeweatsagsdfsad",
  5. "userRef":"asdfsadfsa","accountType":"REAL",balance":43},
  6. "code":"2200",
  7. "msg":null,
  8. "msgRef":null,
  9. "successAndNotNull":true,
  10. "failedOrNull":false,
  11. "failed":false,
  12. "failedAndNull":false}`

Then I extract the data by doing this:

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

and I end up with this String:

  1. "{"ref":"safdasfdwaer",
  2. "userRef":"fdgsgdsgdsfg",
  3. "accountType":"REAL",
  4. "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

  1. val jsonObj: Any!

由于您的方法实际上返回一个字符串(因为它以 toString() 结尾)

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

只需编写

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

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

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

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

  1. val jsonObj : Any!

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

  1. JSONObject(serverResponse.toString()).get(&quot;data&quot;).toString()

Just write

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

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

  1. val result: Map&lt;String, Any&gt; =
  2. 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:

确定