Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON array and JSON Object in swift

Tags:

json

ios

swift

I want do this JSON in Swift. But i cant do this....

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

My swift code returns this:

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

This is my code:

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

This is my input:

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

This is output

{
    date = "2016-08-25 18:52:30 +0000";
    observation = "";
    products =     (
            {
                name = cappuccino;
                quantity = 1;
            }
    );
    room = Platinium;
}

I created a request to send the two products, but the code prints only the last product.

like image 993
Guilherme Abreu Avatar asked Dec 31 '25 21:12

Guilherme Abreu


1 Answers

Create a new prodArray array which holds all the prod dictionary(name and quantity.) Set this prodArray for para array corresponding to products key.

Issue in your code:- In your forin loop, you are over-riding the value corresponding to "products" key.

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")
like image 107
pkc456 Avatar answered Jan 02 '26 11:01

pkc456