简体   繁体   中英

String to JSON Object Convert iOS Swift

From the Server, I am receiving the below string as (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

I am converting a string to JSONObject but as my string is invalid, therefore below code not converting it.

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? Or I have to convert string to json and then convert to JSONObject?

Since the string is not valid JSON you have to convert it manually.

The code

  • Removes the leading and trailing braces.
  • Splits the string by ", " .
  • Converts each item to [String:Int] .

It assumes that all keys are String and all values are 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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