The string to convert:
[{"description": "Hi","id":2,"img":"hi.png"},{"description": "pet","id":10,"img":"pet.png"},{"description": "Hello! :D","id":12,"img":"hello.png"}]
The code to convert the string:
var json = JSON(stringLiteral: stringJSON)
The string is converted to JSON and when I try to count how many blocks are inside this JSON (expected answer = 3), I get 0.
print(json.count)
Console Output: 0
What am I missing? Help is very appreciated.
String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.
Actually, there was a built-in function in SwifyJSON called parse
/** Create a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ public static func parse(string:String) -> JSON { return string.dataUsingEncoding(NSUTF8StringEncoding) .flatMap({JSON(data: $0)}) ?? JSON(NSNull()) }
Note that
var json = JSON.parse(stringJSON)
its now changed to
var json = JSON.init(parseJSON:stringJSON)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With