在swift中创建JSON数组和JSON对象

时间:2016-08-25 18:45:53

标签: ios json swift

我想在Swift中使用这个JSON。但我不能这样做....

select B.*, 
(select top 1 A.idA from A where A.data<=B.data order by A.data) as closestA_ID 
from B

我的快速代码返回:

{
    "room": "Platinum",
    "products": [{
        "name": "Agua",
         "quantity": 2
},
{   
    "name":"Cafe",
    "quantity": 4
}],
    "observation": "",
    "date": "2016-08-15 12:00:00"
}

这是我的代码:

{
    date = "2016-08-25 18:16:28 +0000";
    observation = "";
    products =     (
            {
                name = cafe;
                quantity = 1;
            }
    );
    room = Platinium;

这是我的意见:

let para:NSMutableDictionary = NSMutableDictionary()
let prod: NSMutableDictionary = NSMutableDictionary()

para.setValue(String(receivedString), forKey: "room")
para.setValue(observationString, forKey: "observation")
para.setValue(stringDate, forKey: "date")

for product in products{
    prod.setValue(product.name, forKey: "name")
    prod.setValue(product.quantity, forKey: "quantity")
    para.setObject([prod], forKey: "products")
}

这是输出

{
    name = coffe;
    quantity = 2;
}
{
    name = cappuccino;
    quantity = 1;
}

我创建了发送这两种产品的请求,但代码只打印了最后一个产品。

2 个答案:

答案 0 :(得分:7)

创建一个新的prodArray数组,其中包含所有prod字典(名称和数量。)将此prodArray设置为与para键对应的products数组。

您的代码中出现问题: - 在您的forin循环中,您将覆盖与"products"键对应的值。

let para:NSMutableDictionary = NSMutableDictionary()
let prodArray:NSMutableArray = NSMutableArray()

para.setValue(String(receivedString), forKey: "room")
para.setValue(observationString, forKey: "observation")
para.setValue(stringDate, forKey: "date")

for product in products
{
    let prod: NSMutableDictionary = NSMutableDictionary()
    prod.setValue(product.name, forKey: "name")
    prod.setValue(product.quantity, forKey: "quantity")
    prodArray.addObject(prod)
}

para.setObject(prodArray, forKey: "products")

答案 1 :(得分:3)

您需要在for循环中移动let prod: NSMutableDictionary = NSMutableDictionary()并在for循环后移动para.setObject([prod], forKey: "products"),但您还需要更改,以便创建每个prod并将其添加到数组中循环,然后在循环后将该数组添加到para

您当前的代码不断更换,而不是添加,最后只有最后一个。