简体   繁体   中英

How to convert JSON to swift 3

Nowhere I can not find how to make a json readable type. Suppose there { "x": 5, "b": 6} I would like to get as

{  
"x":5
},
{  
"b":6
}

Keys are not known

I am doing so

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
}

Comes:

["x": 5, "b": 6]
var tempJson : NSString = ""
userCredentials = //pass your dictionary here

    do
    {

        let jsonData = try JSONSerialization.data(withJSONObject: userCredentials, options: JSONSerialization.WritingOptions.prettyPrinted)
        tempJson = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)!
print(tempJson)

    }
    catch let error as NSError
    {
        print(error.description)

    }

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