1

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?

3
  • The server response is not valid JSON. Commented Oct 28, 2017 at 6:34
  • Yes I know, thats y I have to convert it Commented Oct 28, 2017 at 6:35
  • is there any way to do that? Commented Oct 28, 2017 at 6:35

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, you are right, let me try it, thanks for your response @vadian
Thanks, man, I changed the code little bit for my requirements. Now the result can be ended/decoded in JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.