How to convert a string into JSON using SwiftyJSON

21,575

Solution 1

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.

Solution 2

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)

Solution 3

There is a built-in parser in SwiftyJSON:

let json = JSON.init(parseJSON: responseString)

Don't forget to import SwiftyJSON!

Solution 4

I'm using as follows:

let yourString = NSMutableString()

let dataToConvert = yourString.data(using: String.Encoding.utf8.rawValue)

let json = JSON(data: dataToConvert!)

print("\nYour string: " + String(describing: json))

Solution 5

Swift4

let json = string.data(using: String.Encoding.utf8).flatMap({try? JSON(data: $0)}) ?? JSON(NSNull())
Share:
21,575
Gabo Cuadros Cardenas
Author by

Gabo Cuadros Cardenas

Young IOS Developer, learn from my-self and Old Rock music lover 🤘🏼! :D

Updated on June 26, 2021

Comments

  • Gabo Cuadros Cardenas
    Gabo Cuadros Cardenas almost 3 years

    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.