Search code examples
iosjsonswiftswifty-json

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.

print(json.count)

Console Output: 0

What am I missing? Help is very appreciated.


Solution

  • I fix it on this way.

    I will use the variable "string" as the variable what contains the JSON.

    1.

    encode the sting with NSData like this

    var encodedString : NSData = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
    
    1. un-encode the string encoded (this may be sound a little bit weird hehehe):

      var finalJSON = JSON(data: encodedString)

    Then you can do whatever you like with this JSON.

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

    finalJSON.count or print(finalJSON[0]) or whatever you like to do.