0

Im trying to covert this string into a dictionary

{
    "sender_id": 7,
    "Sender_name": Testchumthree Tester,
    "message": 42,
    "Sender_image": https://graph.facebook.com/v2.10/281359099024687/picture?type=normal,
    "timestamp": "0",
    "group_id": 50
}

Below is what i found so far.

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

But this i get an error saying the data is not in the correct format. Any help would be much appreciated.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 2
    This is probably because of the nested double quotes. Anyway, as I explain in my [answer](https://stackoverflow.com/a/30480777/2227743) this code is only a convenience method to convert a simple JSON string *if you don't have the original JSON data*. **Please instead convert the JSON data directly to an object (without converting it to a string before trying to convert it to an object).** – Eric Aya Dec 07 '17 at 12:23
  • Please reformat your json – Yitzchak Dec 07 '17 at 12:23
  • 1
    The error is right. All JSON keys and string values are required to be wrapped in double quotes. – vadian Dec 07 '17 at 12:29

1 Answers1

1

The problem with your JSON is that strings are not properly formatted. There must be quotes around them and depending on the library "/" must also be escaped.

Try using this:

{
    "sender_id": 7,
    "Sender_name": "Testchumthree Tester",
    "message": 42,
    "Sender_image": "https:\/\/graph.facebook.com\/v2.10\/281359099024687\/picture?type=normal",
    "timestamp": "0",
    "group_id": 50
}
Julian
  • 8,808
  • 8
  • 51
  • 90
  • 1
    Good answer. One small note: apart from buggy implementations, `/` does not need to be escaped. *All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).* - [JSON](https://www.ietf.org/rfc/rfc4627.txt) – Jeffery Thomas Dec 07 '17 at 16:25