快速创建 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29512839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:49:58  来源:igfitidea点击:

Create JSON in swift

jsonswiftobject

提问by Yestay Muratov

I need to create JSON like this:

我需要像这样创建 JSON:

Order = {   type_id:'1',model_id:'1',

   transfer:{
     startDate:'10/04/2015 12:45',
     endDate:'10/04/2015 16:00',
     startPoint:'Ул. Момышулы, 45',
     endPoint:'Аэропорт Астаны'
   },
   hourly:{
     startDate:'10/04/2015',
     endDate:'11/04/2015',
     startPoint:'ЖД Вокзал',
     endPoint:'',
     undefined_time:'1'
   },
   custom:{
     startDate:'12/04/2015',
     endDate:'12/04/2015',
     startPoint:'Астана',
     endPoint:'Павлодар',
     customPrice:'50 000'
   },
    commentText:'',
    device_type:'ios'
};

The problem is that I can not create valid JSON. Here is how I create object:

问题是我无法创建有效的 JSON。这是我创建对象的方式:

let jsonObject: [AnyObject]  = [
        ["type_id": singleStructDataOfCar.typeID, "model_id": singleStructDataOfCar.modelID, "transfer": savedDataTransfer, "hourly": savedDataHourly, "custom": savedDataReis, "device_type":"ios"]
    ]

where savedDataare dictionaries:

savedData字典在哪里:

let savedData: NSDictionary = ["ServiceDataStartDate": singleStructdata.startofWork, 
"ServiceDataAddressOfReq": singleStructdata.addressOfRequest, 
"ServiceDataAddressOfDel": singleStructdata.addressOfDelivery, 
"ServiceDataDetailedText": singleStructdata.detailedText, "ServiceDataPrice": singleStructdata.priceProposed]

When I use only strings creating my JSON object everything works fine. However when I include dictionaries NSJSONSerialization.isValidJSONObject(value)returns false. How can I create a valid dictionary?

当我只使用字符串创建我的 JSON 对象时,一切正常。但是,当我包含字典时NSJSONSerialization.isValidJSONObject(value)返回false. 如何创建有效的字典?

回答by Matt Mathias

One problem is that this code is not of type Dictionary.

一个问题是这段代码不是类型的Dictionary

let jsonObject: [Any]  = [
    [
         "type_id": singleStructDataOfCar.typeID,
         "model_id": singleStructDataOfCar.modelID, 
         "transfer": savedDataTransfer, 
         "hourly": savedDataHourly, 
         "custom": savedDataReis, 
         "device_type":"iOS"
    ]
]

The above is an Arrayof AnyObjectwith a Dictionaryof type [String: AnyObject]inside of it.

上面是一个Arrayof AnyObject,里面有一个Dictionaryof 类型[String: AnyObject]

Try something like this to match the JSON you provided above:

尝试这样的事情来匹配你上面提供的 JSON:

let savedData = ["Something": 1]

let jsonObject: [String: Any] = [ 
    "type_id": 1,
    "model_id": 1,
    "transfer": [
        "startDate": "10/04/2015 12:45",
        "endDate": "10/04/2015 16:00"
    ],
    "custom": savedData
]

let valid = JSONSerialization.isValidJSONObject(jsonObject) // true

回答by zeeshan

For Swift 3.0, as of December 2016, this is how it worked for me:

对于 Swift 3.0,截至 2016 年 12 月,这对我来说是这样的:

let jsonObject: NSMutableDictionary = NSMutableDictionary()

jsonObject.setValue(value1, forKey: "b")
jsonObject.setValue(value2, forKey: "p")
jsonObject.setValue(value3, forKey: "o")
jsonObject.setValue(value4, forKey: "s")
jsonObject.setValue(value5, forKey: "r")

let jsonData: NSData

do {
    jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions()) as NSData
    let jsonString = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
    print("json string = \(jsonString)")                                    

} catch _ {
    print ("JSON Failure")
}

EDIT 2018: I now use SwiftyJSON library to save time and make my development life easier and better. Dealing with JSON natively in Swift is an unnecessary headache and pain, plus wastes too much time, and creates code which is hard to read and write, and hence prone to lots of errors.

编辑 2018:我现在使用 SwiftyJSON 库来节省时间并使我的开发生活更轻松、更好。在 Swift 中原生处理 JSON 是一种不必要的头痛和痛苦,而且浪费了太多时间,并且创建了难以读写的代码,因此容易出现很多错误。

回答by A.G

Creating a JSON String:

创建 JSON 字符串:

let para:NSMutableDictionary = NSMutableDictionary()
para.setValue("bidder", forKey: "username")
para.setValue("day303", forKey: "password")
para.setValue("authetication", forKey: "action")
let jsonData = try! NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions.allZeros)
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
print(jsonString)

回答by user462990

This worked for me... Swift 2

这对我有用...... Swift 2

static func checkUsernameAndPassword(username: String, password: String) -> String?{
    let para:NSMutableDictionary = NSMutableDictionary()
        para.setValue("demo", forKey: "username")
        para.setValue("demo", forKey: "password")
       // let jsonError: NSError?
    let jsonData: NSData
    do{
        jsonData = try NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions())
        let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
        print("json string = \(jsonString)")
        return jsonString

    } catch _ {
        print ("UH OOO")
        return nil
    }
}

回答by Peheje

Check out https://github.com/peheje/JsonSerializerSwift

查看https://github.com/peheje/JsonSerializerSwift

Use case:

用例:

//Arrange your model classes
class Object {
  var id: Int = 182371823
  }
class Animal: Object {
  var weight: Double = 2.5
  var age: Int = 2
  var name: String? = "An animal"
  }
class Cat: Animal {
  var fur: Bool = true
}

let m = Cat()

//Act
let json = JSONSerializer.toJson(m)

//Assert
let expected = "{\"fur\": true, \"weight\": 2.5, \"age\": 2, \"name\": \"An animal\", \"id\": 182371823}"
stringCompareHelper(json, expected) //returns true

Currently supports standard types, optional standard types, arrays, arrays of nullables standard types, array of custom classes, inheritance, composition of custom objects.

目前支持标准类型、可选标准类型、数组、可为空的标准类型数组、自定义类数组、继承、自定义对象的组合。

回答by Baran Emre

? Swift 4.1, April 2018

? Swift 4.1,2018 年 4 月

Here is a more general approachthat can be used to create a JSON string by using values from a dictionary:

这是一种更通用的方法,可用于通过使用字典中的值创建 JSON 字符串:

struct JSONStringEncoder {
    /**
     Encodes a dictionary into a JSON string.
     - parameter dictionary: Dictionary to use to encode JSON string.
     - returns: A JSON string. `nil`, when encoding failed.
     */
    func encode(_ dictionary: [String: Any]) -> String? {
        guard JSONSerialization.isValidJSONObject(dictionary) else {
            assertionFailure("Invalid json object received.")
            return nil
        }

        let jsonObject: NSMutableDictionary = NSMutableDictionary()
        let jsonData: Data

        dictionary.forEach { (arg) in
            jsonObject.setValue(arg.value, forKey: arg.key)
        }

        do {
            jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
        } catch {
            assertionFailure("JSON data creation failed with error: \(error).")
            return nil
        }

        guard let jsonString = String.init(data: jsonData, encoding: String.Encoding.utf8) else {
            assertionFailure("JSON string creation failed.")
            return nil
        }

        print("JSON string: \(jsonString)")
        return jsonString
    }
}

How to use it:

如何使用它

let exampleDict: [String: Any] = [
        "Key1" : "stringValue",         // type: String
        "Key2" : boolValue,             // type: Bool
        "Key3" : intValue,              // type: Int
        "Key4" : customTypeInstance,    // type: e.g. struct Person: Codable {...}
        "Key5" : customClassInstance,   // type: e.g. class Human: NSObject, NSCoding {...}
        // ... 
    ]

    if let jsonString = JSONStringEncoder().encode(exampleDict) {
        // Successfully created JSON string.
        // ... 
    } else {
        // Failed creating JSON string.
        // ...
    }

Note: If you are adding instances of your custom types (structs) into the dictionary make sure your types conform to the Codableprotocol and if you are adding objects of your custom classes into the dictionary make sure your classes inherit from NSObjectand conform to the NSCodingprotocol.

注意:如果您将自定义类型(结构)的实例添加到字典中,请确保您的类型符合Codable协议,如果您将自定义类的对象添加到字典中,请确保您的类继承NSObject并符合NSCoding协议。