Swift - 为什么我的JSON对象元素只添加最后一个数组元素?

时间:2018-02-27 21:11:17

标签: swift

我的JSON对象有问题。除了idQty部分之外,一切都工作得很好,创建并打印出我的JSON对象。它只打印最后一个键值结果。我假设我的for循环有问题。如果有人能够指出我出错的地方,那将会有很大的帮助。

以下代码:

struct Order: Codable {
    let idQty: [IdQty]
    let collection: String
    let name: String
    let phone: Int
    let doorNum: Int
    let street: String
    let postcode: String
}

struct IdQty: Codable {
    let itemId: Int
    let qty: Int
}

class CheckoutServer: NSObject, URLSessionDataDelegate {

    var inputVals = [Int:Int]()

    var idQty = [IdQty]()

    var collection = String()
    var name = String()
    var phone = Int()
    var doorNum = Int()
    var street = String()
    var postcode = String()

    var request = URLRequest(url: NSURL(string: "http://192.168.1.100/api/AddOrder.php")! as URL)

    func downloadItems() {

        for(key,value) in inputVals {
            idQty = [IdQty(itemId: key,qty: value)]
        }

        let order = Order(idQty: idQty,collection: collection,name: name,phone: phone,doorNum: doorNum,street: street,postcode: postcode)
        let encodedOrder = try? JSONEncoder().encode(order)
        var json: Any?

        request.httpMethod = "POST"



        if let data = encodedOrder {
            json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
            if let json = json {

            }
        }
        let postParameters = "json="+String(describing: json!)

        request.httpBody = postParameters.data(using: .utf8)
        print(String(describing: json!))

        let defaultSession = URLSession(configuration: URLSessionConfiguration.default)

        let task = defaultSession.dataTask(with: request) { (data, response, error) in

            if error != nil {
                print("Failed to upload data at Menu Type Items")
            } else {
                print("Data uploaded")
            }
        }
        task.resume()
    }

}

以下是输出。 'idQty'部分只返回[Int:Int]字典中的最后一个条目:

 {
    collection = Delivery;
    doorNum = 4;
    idQty =     (
                {
            itemId = 14;
            qty = 2;
        }
    );
    name = James;
    phone = 4355345;
    postcode = Test;
    street = TestStreet;
}

1 个答案:

答案 0 :(得分:1)

您应该为数组添加新值,而不是在每次迭代时重新创建它

 for(key,value) in inputVals 
 {
        idQty.append(IdQty(itemId: key,qty: value))
 }