Yes*_*tov 36 json object swift
我需要像这样创建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'
};
Run Code Online (Sandbox Code Playgroud)
问题是我无法创建有效的JSON.这是我创建对象的方式:
let jsonObject: [AnyObject] = [
["type_id": singleStructDataOfCar.typeID, "model_id": singleStructDataOfCar.modelID, "transfer": savedDataTransfer, "hourly": savedDataHourly, "custom": savedDataReis, "device_type":"ios"]
]
Run Code Online (Sandbox Code Playgroud)
savedData词典在哪里:
let savedData: NSDictionary = ["ServiceDataStartDate": singleStructdata.startofWork,
"ServiceDataAddressOfReq": singleStructdata.addressOfRequest,
"ServiceDataAddressOfDel": singleStructdata.addressOfDelivery,
"ServiceDataDetailedText": singleStructdata.detailedText, "ServiceDataPrice": singleStructdata.priceProposed]
Run Code Online (Sandbox Code Playgroud)
当我只使用字符串创建我的JSON对象时,一切正常.但是当我包含词典NSJSONSerialization.isValidJSONObject(value)返回时false.如何创建有效的字典?
Mat*_*ias 62
一个问题是此代码不是类型Dictionary.
let jsonObject: [Any] = [
[
"type_id": singleStructDataOfCar.typeID,
"model_id": singleStructDataOfCar.modelID,
"transfer": savedDataTransfer,
"hourly": savedDataHourly,
"custom": savedDataReis,
"device_type":"iOS"
]
]
Run Code Online (Sandbox Code Playgroud)
以上是一个Array的AnyObject与Dictionary类型的[String: AnyObject]在其内部.
尝试这样的方法来匹配您在上面提供的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
Run Code Online (Sandbox Code Playgroud)
zee*_*han 23
对于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")
}
Run Code Online (Sandbox Code Playgroud)
编辑2018:我转向SwiftyJSON以节省时间并使我的开发生活更轻松,更好.在Swift中本地处理JSON是一种不必要的头痛和痛苦,加上浪费了太多时间,并且创建了难以读写的代码,因此容易出现大量错误.
A.G*_*A.G 10
创建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)
Run Code Online (Sandbox Code Playgroud)
\xe2\x80\xa2 Swift 4.1,2018 年 4 月
\n\n以下是一种更通用的方法,可用于通过使用字典中的值来创建 JSON 字符串:
\n\nstruct JSONStringEncoder {\n /**\n Encodes a dictionary into a JSON string.\n - parameter dictionary: Dictionary to use to encode JSON string.\n - returns: A JSON string. `nil`, when encoding failed.\n */\n func encode(_ dictionary: [String: Any]) -> String? {\n guard JSONSerialization.isValidJSONObject(dictionary) else {\n assertionFailure("Invalid json object received.")\n return nil\n }\n\n let jsonObject: NSMutableDictionary = NSMutableDictionary()\n let jsonData: Data\n\n dictionary.forEach { (arg) in\n jsonObject.setValue(arg.value, forKey: arg.key)\n }\n\n do {\n jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)\n } catch {\n assertionFailure("JSON data creation failed with error: \\(error).")\n return nil\n }\n\n guard let jsonString = String.init(data: jsonData, encoding: String.Encoding.utf8) else {\n assertionFailure("JSON string creation failed.")\n return nil\n }\n\n print("JSON string: \\(jsonString)")\n return jsonString\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n如何使用它:
\n\nlet exampleDict: [String: Any] = [\n "Key1" : "stringValue", // type: String\n "Key2" : boolValue, // type: Bool\n "Key3" : intValue, // type: Int\n "Key4" : customTypeInstance, // type: e.g. struct Person: Codable {...}\n "Key5" : customClassInstance, // type: e.g. class Human: NSObject, NSCoding {...}\n // ... \n ]\n\n if let jsonString = JSONStringEncoder().encode(exampleDict) {\n // Successfully created JSON string.\n // ... \n } else {\n // Failed creating JSON string.\n // ...\n }\nRun Code Online (Sandbox Code Playgroud)\n\n注意:如果您要将自定义类型(结构)的实例添加到字典中,请确保您的类型符合协议Codable;如果您要将自定义类的对象添加到字典中,请确保您的类继承NSObject并符合NSCoding协议。
Swift 5 - 6/30/21
Adopt the Codable protocol (similar to interface in other programming languages)
struct ConfigRequestBody: Codable {
var systemid: String
var password: String
var request: String = "getconfig"
init(systemID: String, password: String){
self.systemid = systemID
self.password = password
}
}
Run Code Online (Sandbox Code Playgroud)
Create instance of struct/class that you want to turn into JSON:
let requestBody = ConfigRequestBody(systemID: systemID, password: password)
Run Code Online (Sandbox Code Playgroud)
Encode the object into JSON using a JSONEncoder. 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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74630 次 |
| 最近记录: |