我想以下面的格式创建JSON。以给定格式创建JSON Swift
{
"userID": "1234",
"cart_items": {
"1": {
"item_Seq_no": 1,
"catalog_id": 234,
"qty": 1,
"amount": 100
},
"2": {
"item_Seq_no": 2,
"catalog_id": 45,
"qty": 3,
"amount": 300
},
"3": {
"item_Seq_no": 3,
"catalog_id": 177,
"qty": 2,
"amount": 200
}
}
}
我在下面写的代码并不是完全以上述格式创建的。
let arr:NSMutableArray = []
for i in 0...KCatalog.catalogValues.count-1
{
let seqnum1 = String(i + 1)
let param2:[String: AnyObject] = [
seqnum1: [
"item_Seq_no" : i+1,
"catalog_id" : ((KCatalog.catalogValues[i] as! catalogInfo).catalog_id),
"qty" : orderedQuantity[i],
"amount" : totalQuantityPrice[i],
],
]
arr.addObject(param2)
}
print(arr)
let param1:NSMutableDictionary = [
"cart_items" : arr,
"userID":"asdf",
]
print(param1)
let data1 = try! NSJSONSerialization.dataWithJSONObject(param1, options: NSJSONWritingOptions.PrettyPrinted)
let json = String(data: data1, encoding: NSUTF8StringEncoding)
if let json = json {
print(json)
}
我想知道给定的格式是否正确。如果是的话,请给我建议,使其在上述格式
输出我得到是
{
"userID": "asdf",
"cart_items": [
{
"1": {
"item_Seq_no": 1,
"amount": 10,
"catalog_id": "1",
"qty": 1
}
},
{
"2": {
"item_Seq_no": 2,
"amount": 15,
"catalog_id": "2",
"qty": 1
}
},
{
"3": {
"item_Seq_no": 3,
"amount": 0,
"catalog_id": "3",
"qty": 0
}
}
]
}
据萨曼莎回答我得到以下输出
{
"userID": "asdf",
"cart_items": {
"1": {
"1": {
"item_Seq_no": 1,
"amount": 10,
"catalog_id": "1",
"qty": 1
}
},
"2": {
"2": {
"item_Seq_no": 2,
"amount": 15,
"catalog_id": "2",
"qty": 1
}
},
"3": {
"3": {
"item_Seq_no": 3,
"amount": 0,
"catalog_id": "3",
"qty": 0
}
}
}
}
可以打印你的JSON和检查自己是否正确与否? –
@Tinu Dahiya我编辑我的问题,并添加我得到的输出是不是在给定的格式 – VJVJ
在预期的结果'cart_items'似乎是一个字典,但在你的代码,它看起来像你将它添加为一个数组,这可能是问题吗? – Samantha