【问题标题】:How to parse string in swift如何快速解析字符串
【发布时间】:2020-02-28 22:45:45
【问题描述】:

我的json是这样的:

"billerdetails": [
{
"id": "1",
"bname": "ACT Fibernet",
"bcustomerparms": "[{\"paramName\":\"Account Number/User Name\",\"dataType\":\"ALPHANUMERIC\",\"optional\":\"false\",\"minLength\":\"1\",\"maxLength\":\"50\"}]",
"breponseParams": "[{\"amtBreakupList\":[{\"amtBreakup\":\"BASE_BILL_AMOUNT\"}]}]",
......

在这里我可以得到bcustomerparms。但在这里我需要 bcustomerparms:paramName 值,例如(帐号/用户名)在一个 virable 中.. 为此我编写了如下代码,但我无法在 vairable 中获取帐号/用户名。

请在下面的代码中帮助我:

do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
//print("the all make payment json is \(jsonObj)")

let billerdetailsArray = jsonObj["billerdetails"] as! [[String: Any]]

for billerdetail in billerdetailsArray {

    self.categoryName = billerdetail["bname"] as? String
    var customrParams = billerdetail["bcustomerparms"]
    print("biller customrParams \(customrParams)") 
 }

// 这里我得到 bcustomerparms

biller customrParams Optional([{"paramName":"Connection ID","dataType":"ALPHANUMERIC","optional":"false","minLength":"8","maxLength":"10"} ])

但在这里我只想要 paramName 值如何获取该值。请在上面的代码中帮助我。

【问题讨论】:

  • 表示您只需要 customrParams 中的“paramName”吗?
  • @SGDev 是的,只有一个变量中的连接 ID 等参数名称值..
  • 您对 JSON 负责吗?如果是,请不要发送嵌套 JSON(另一个 JSON 字符串作为字典值),这是非常糟糕的做法。
  • @vadian,不,我正在从后端团队获取 JSON
  • 然后要求后端团队发送更合理的JSON(以及更一致的键名)。

标签: json swift string dictionary


【解决方案1】:

bcustomerparms值是字符串不是字典数组,你可以试试

let customrParams = billerdetail["bcustomerparms"] as! String
let res = try JSONSerialization.jsonObject(with:Data(customrParams.utf8)) as! [[String: Any]]
for item in res {
  print(item["paramName"])
}

【讨论】:

  • 我已经尝试过你的答案,它正在工作,我已经接受了你的答案,但我需要更多帮助才能使用 didSelectRowAt indexPath 将该 paramName 发送到 nextVC
  • 非常感谢您的帮助!!我能做剩下的工作,为你点赞!!
猜你喜欢
  • 2023-02-22
  • 2010-09-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多