快速创建JSON [英] Create JSON in swift
问题描述
我需要这样创建JSON:
I need to create JSON like this:
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'
};
问题是我无法创建有效的JSON. 这是我创建对象的方式:
The problem is that I can not create valid 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"]
]
其中savedData
是词典:
let savedData: NSDictionary = ["ServiceDataStartDate": singleStructdata.startofWork,
"ServiceDataAddressOfReq": singleStructdata.addressOfRequest,
"ServiceDataAddressOfDel": singleStructdata.addressOfDelivery,
"ServiceDataDetailedText": singleStructdata.detailedText, "ServiceDataPrice": singleStructdata.priceProposed]
当我仅使用字符串创建JSON对象时,一切正常.但是,当我包含字典时,NSJSONSerialization.isValidJSONObject(value)
返回false
.如何创建有效的词典?
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?
推荐答案
一个问题是该代码不是Dictionary
类型.
One problem is that this code is not of type Dictionary
.
let jsonObject: [Any] = [
[
"type_id": singleStructDataOfCar.typeID,
"model_id": singleStructDataOfCar.modelID,
"transfer": savedDataTransfer,
"hourly": savedDataHourly,
"custom": savedDataReis,
"device_type":"iOS"
]
]
上面是AnyObject
的Array
,内部是[String: AnyObject]
类型的Dictionary
.
The above is an Array
of AnyObject
with a Dictionary
of type [String: AnyObject]
inside of it.
尝试类似这样的方法以匹配您在上面提供的JSON:
Try something like this to match the JSON you provided above:
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
这篇关于快速创建JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!