简体   繁体   English

字符串到JSON对象的转换iOS Swift

[英]String to JSON Object Convert iOS Swift

From the Server, I am receiving the below string as (AnyHashable : String) 从服务器,我收到以下字符串作为(AnyHashable:String)

{Type:1, OrderId:174}

I know it is not a valid Json String, but I have to deal with Type and OrderId separately 我知道这不是有效的Json字符串,但我必须分别处理TypeOrderId

I am converting a string to JSONObject but as my string is invalid, therefore below code not converting it. 我正在将字符串转换为JSONObject,但是由于我的字符串无效,因此下面的代码无法将其转换。

if let tag = notification.request.content.userInfo["tag"]{
        if let json = try? JSONSerialization.data(withJSONObject: tag, options: []) {
            // here `json` is your JSON data
            print(json)
        }
    }

Anyone can suggest what should I do to get Type and OrderId value so I can handle the response? 任何人都可以建议我该如何获取Type和OrderId值,以便我可以处理响应? Or I have to convert string to json and then convert to JSONObject? 还是我必须将字符串转换为json,然后再转换为JSONObject?

Since the string is not valid JSON you have to convert it manually. 由于该字符串不是有效的JSON,因此您必须手动对其进行转换。

The code 编码

  • Removes the leading and trailing braces. 删除前括号和尾括号。
  • Splits the string by ", " . ", "分割字符串。
  • Converts each item to [String:Int] . 将每个项目转换为[String:Int]

It assumes that all keys are String and all values are Int 假定所有键均为String ,所有值均为Int

let string = "{Type:1, OrderId:174}"
let trimmedString = string.trimmingCharacters(in: CharacterSet(charactersIn: "{}"))
let components = trimmedString.components(separatedBy: ", ")
var result = [String:Int]()
_ = components.map { item in
    let keyValue = item.components(separatedBy: ":")
    result[keyValue[0]] = Int(keyValue[1])
}

Console: 安慰:

["Type": 1, "OrderId": 174]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM