Creating json in swift

I want to createa json like this in swift:

{
    "test1": 0,
    "test2": 1435659978,
    "test3": 1430479596
}

How can I create this json?


Solution 1:

Create your object, in this case a Dictionary:

let dic = ["test1":0, "test2":1435659978, "test3":1430479596]

Create the JSON data from the object:

do {
    let dic = ["test1":0, "test2":1435659978, "test3":1430479596]
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
} catch let error as NSError {
    print(error)
}

Use the JSON data as a String if you need it:

do {
    let dic = ["test1":0, "test2":1435659978, "test3":1430479596]
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
    let str = String(data: jsonData, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
    print(error)
}

Solution 2:

Check out this github page instead

I created a small class that can take any Swift class object and turn it into JSON. Can handle composition.

import Foundation
class JSONSerializer {
static func toJson(object: Any) -> String {
var json = "{"
let mirror = Mirror(reflecting: object)
let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)!
let size = mirror.children.count
var index = 0
for (optionalPropertyName, value) in mirrorChildrenCollection {
let propertyName = optionalPropertyName!
let property = Mirror(reflecting: value)
var handledValue = String()
if value is Int || value is Double || value is Float || value is Bool {
                handledValue = String(value ?? "null")
            }
else if let array = value as? [Int?] {
                handledValue += "["
for (index, value) in array.enumerate() {
                    handledValue += value != nil ? String(value!) : "null"
                    handledValue += (index < array.count-1 ? ", " : "")
                }
                handledValue += "]"
            }
else if let array = value as? [Double?] {
                handledValue += "["
for (index, value) in array.enumerate() {
                    handledValue += value != nil ? String(value!) : "null"
                    handledValue += (index < array.count-1 ? ", " : "")
                }
                handledValue += "]"
            }
else if let array = value as? [Float?] {
                handledValue += "["
for (index, value) in array.enumerate() {
                    handledValue += value != nil ? String(value!) : "null"
                    handledValue += (index < array.count-1 ? ", " : "")
                }
                handledValue += "]"
            }
else if let array = value as? [Bool?] {
                handledValue += "["
for (index, value) in array.enumerate() {
                    handledValue += value != nil ? String(value!) : "null"
                    handledValue += (index < array.count-1 ? ", " : "")
                }
                handledValue += "]"
            }
else if let array = value as? [String?] {
                handledValue += "["
for (index, value) in array.enumerate() {
                    handledValue += value != nil ? "\"\(value!)\"" : "null"
                    handledValue += (index < array.count-1 ? ", " : "")
                }
                handledValue += "]"
            }
else if let array = value as? [String] {
                handledValue += "["
for (index, value) in array.enumerate() {
                    handledValue += "\"\(value)\""
                    handledValue += (index < array.count-1 ? ", " : "")
                }
                handledValue += "]"
            }
else if let array = value as? NSArray {
                handledValue += "["
for (index, value) in array.enumerate() {
                    handledValue += "\(value)"
                    handledValue += (index < array.count-1 ? ", " : "")
                }
                handledValue += "]"
            }
else if property.children.count > 0 {
                handledValue = toJson(value)
            }
else {
                handledValue = String(value) != "nil" ? "\"\(value)\"" : "null"
            }
            json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "")
++index
        }
        json += "}"
return json
    }
}
//Test nonsense data
class Nutrient {
var name = "VitaminD"
var amountUg = 4.2
var intArray = [1, 5, 9]
var stringArray = ["nutrients", "are", "important"]
}
class Fruit {
var name: String = "Apple"
var color: String? = nil
var weight: Double = 2.1
var diameter: Float = 4.3
var radius: Double? = nil
var isDelicious: Bool = true
var isRound: Bool? = nil
var nullString: String? = nil
var date = NSDate()
var optionalIntArray: [Int?] = [1, 5, 3, 4, nil, 6]
var doubleArray: [Double?] = [nil, 2.2, 3.3, 4.4]
var stringArray: [String] = ["one", "two", "three", "four"]
var optionalArray: [Int] = [2, 4, 1]
var optionalStringArray: [String?] = ["topdoge", nil, "hejsan"]
var nutrient: Nutrient = Nutrient()
var nutrientNull: Nutrient? = Nutrient()
var nutrientNullN: Nutrient? = nil
func eat() {
print("eating the fruit")
    }
}
var fruit = Fruit()
var json = JSONSerializer.toJson(fruit)
print(json)

Paste it into a playground to try. It's Swift 2.0 and requires XCode beta.

https://gist.github.com/peheje/cc3618253d4f38ea4885