1

I want to createa json like this in swift:

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

How can I create this json?

1
  • I have created a Framework for this, you can check it out on GitHub github.com/CodetrixStudio/CSJson It is able to serialize as well deserialize. Commented Feb 3, 2016 at 6:24

2 Answers 2

4

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)
}
Sign up to request clarification or add additional context in comments.

5 Comments

I will add items to json via loop. Is there something like this: dic.add("test1",0) ?
No, do it like this: dic["test1"] = 0
Last question: What is the type of "dic" variable?
The type is [String:Int], a dictionary with type String as key and type Int as value. It is inferred by the compiler because I didn't declare any particular type. I could have written let dic: [String:Int] = ["test1":0, "test2":1435659978, "test3":1430479596] to make things more clear but it wasn't necessary. :)
Worth noting (swift 2.0, Xcode 7) : optionals are not valid data in the json object; if you have those the compiler complains with a cryptic error message. Also, If I didn't assign the json object to a variable there was no build error, but the app would crash in runtime.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.