简体   繁体   English

快速创建 JSON

[英]Create JSON in swift

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.问题是我无法创建有效的 JSON。 Here is how I create object:这是我创建对象的方式:

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

where savedData are 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.当我只使用字符串创建我的 JSON 对象时,一切正常。 However when I include dictionaries NSJSONSerialization.isValidJSONObject(value) returns false .但是,当我包含字典时NSJSONSerialization.isValidJSONObject(value)返回false How can I create a valid dictionary?如何创建有效的字典?

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 Array of AnyObject with a Dictionary of type [String: AnyObject] inside of it.上面是一个AnyObject ArrayAnyObject有一个[String: AnyObject]类型的Dictionary

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

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

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)

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

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.目前支持标准类型、可选标准类型、数组、可为空的标准类型数组、自定义类数组、继承、自定义对象的组合。

• Swift 4.1, April 2018 • Swift 4.1,2018 年 4 月

Here is a more general approach that 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 Codable protocol and if you are adding objects of your custom classes into the dictionary make sure your classes inherit from NSObject and conform to the NSCoding protocol.注意:如果您将自定义类型(结构)的实例添加到字典中,请确保您的类型符合Codable协议,如果您将自定义类的对象添加到字典中,请确保您的类从NSObject继承并符合NSCoding协议。

Swift 5 - 6/30/21斯威夫特 5 - 6/30/21

Adopt the Codable protocol (similar to interface in other programming languages)采用 Codable 协议(类似于其他编程语言中的接口)

struct ConfigRequestBody: Codable {
var systemid: String
var password: String
var request: String = "getconfig"

init(systemID: String, password: String){
    self.systemid = systemID
    self.password = password
}

} }

Create instance of struct/class that you want to turn into JSON:创建要转换为 JSON 的结构/类的实例:

let requestBody = ConfigRequestBody(systemID: systemID, password: password)

Encode the object into JSON using a JSONEncoder .使用JSONEncoder将对象编码为 JSON。 Here I print the string representation so you can see the result:在这里,我打印字符串表示,以便您可以看到结果:

    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    do {
        let result = try encoder.encode(requestBody)
        // RESULT IS NOW JSON-LIKE DATA OBJECT
        if let jsonString = String(data: result, encoding: .utf8){
            // JSON STRING
            print("JSON \(jsonString)")
        }
    } catch {
        print("Your parsing sucks \(error)")
        return nil
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM