34

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

5 Answers5

60

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)
SBotirov
  • 13,872
  • 7
  • 59
  • 81
HamGuy
  • 916
  • 1
  • 7
  • 18
15

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.

peterh
  • 11,875
  • 18
  • 85
  • 108
5

There is a built-in parser in SwiftyJSON:

let json = JSON.init(parseJSON: responseString)

Don't forget to import SwiftyJSON!

BabakHSL
  • 622
  • 1
  • 8
  • 18
2

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))
Machado
  • 14,105
  • 13
  • 56
  • 97
1

Swift4

let json = string.data(using: String.Encoding.utf8).flatMap({try? JSON(data: $0)}) ?? JSON(NSNull())
Maxim Firsoff
  • 2,038
  • 22
  • 28
  • It doesn't compile because $0 is UInt8 and not a valid parameter type for JSON(data:). Despite not compiling, I don't see how this would result in json because it makes an array (flatMap). – Lensflare Nov 05 '18 at 09:46
  • The part `$0` is used within ForEach loops, so it could technically work. – Unterbelichtet Apr 13 '21 at 14:21