Naveed Ahmad
Naveed Ahmad

Reputation: 6737

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?

Upvotes: 1

Views: 259

Answers (1)

vadian
vadian

Reputation: 285079

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]

Upvotes: 2

Related Questions