Gabo Cuadros Cardenas Gabo Cuadros Cardenas - 1 year ago 112
iOS Question

How to convert a string into JSON using SwiftyJSON

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.


Console Output:

What am I missing? Help is very appreciated.

Answer Source

Hi guys i fix it from this way...

note : i will user the variable "string" as the variable what contains the JSON

encode the sting with NSData like this

var encodedString : NSData = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)!

2º un-encode the string encoded (this may be sound a little bit weird hehehe)

var finalJSON = JSON(data: encodedString)

and the u can do what ever u like with this JSON! :D

like get the number of sections in it (this was the real question) with



print(finalJSON[0]) or what ever u like to do..

so, i hope u enjoy the way that i found!

keep coding, Gabriel Cuadros :D

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download