Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在swift中创建json_Swift - Fatal编程技术网

在swift中创建json

在swift中创建json,swift,Swift,我想在swift中创建一个json,如下所示: { "test1": 0, "test2": 1435659978, "test3": 1430479596 } 如何创建此json?创建您的对象,在本例中为字典: let dic = ["test1":0, "test2":1435659978, "test3":1430479596] 从对象创建JSON数据: do { let dic = ["test1":0, "test2":1435659978, "te

我想在swift中创建一个json,如下所示:

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

如何创建此json?

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

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

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

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)
}
我创建了一个小类,它可以接受任何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测试版

我创建了一个小类,它可以接受任何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测试版


我将通过循环向json添加项目。是否有类似的内容:dic.addtest1,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对象分配给变量,则没有生成错误,但应用程序会在运行时崩溃。我将通过循环向json添加项目。是否有类似的内容:dic.addtest1,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对象分配给变量,则没有生成错误,但应用程序会在运行时崩溃。我已经为此创建了一个框架,您可以在GitHub上查看它,它可以序列化也可以反序列化。我已经为此创建了一个框架,您可以在GitHub上查看它,它可以序列化也可以反序列化。