【问题标题】:Creating json in swift快速创建json
【发布时间】:2016-03-22 19:05:15
【问题描述】:

我想在swift中创建一个这样的json:

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

如何创建这个 json?

【问题讨论】:

标签: swift


【解决方案1】:

创建您的对象,在本例中为字典:

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

从对象创建 JSON 数据:

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)
}

如果需要,可以将 JSON 数据用作字符串:

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)
}

【讨论】:

  • 我将通过循环将项目添加到 json。有没有这样的东西: dic.add("test1",0) ?
  • 不,这样做:dic["test1"] = 0
  • 最后一个问题:“dic”变量的类型是什么?
  • 类型为[String:Int],一个以String类型为键、Int类型为值的字典。它是由编译器推断的,因为我没有声明任何特定类型。我本可以写let dic: [String:Int] = ["test1":0, "test2":1435659978, "test3":1430479596] 让事情更清楚,但这没有必要。 :)
  • 值得注意(swift 2.0,Xcode 7):可选项不是 json 对象中的有效数据;如果你有这些,编译器会抱怨一个神秘的错误消息。此外,如果我没有将 json 对象分配给变量,则不会出现构建错误,但应用程序会在运行时崩溃。
【解决方案2】:

Check out this github page instead

我创建了一个小类,它可以接受任何 Swift 类对象并将其转换为 JSON。可以处理合成。

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)

将其粘贴到游乐场尝试。它是 Swift 2.0,需要 XCode 测试版。

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

【讨论】:

    猜你喜欢
    • 2015-06-13
    • 2018-11-13
    • 1970-01-01
    • 2019-08-20
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2016-02-29
    相关资源
    最近更新 更多