简体   繁体   中英

Create an object from JSON response, modify values, and return it in Swift

In an app I recently developed, the client wanted to be able to create a NEW user in their POS system. Their POS system is web-based and has a massive API, so this was easy.

Now they want the app to see if the user exists before creating a duplicate user, which is fine. However, they also want to update the information in the user record if it is a duplicate.

The POS system's API returns an extensive "Customer" JSON response with 250+ fields. I only need to update 4 of those fields.

Is there a way to easily create an object from the "Get Customer" response (it is a multi-dimensional array), edit specific values, and then post that object back as JSON to the "Update Customer" method?

Edit #1

Still having problems wrapping my head around this. To further clarify the process and how it works:

1) API call to get user information 2) User information returned via JSON. The response is a REALLY big, multi-dimensional, response. 3) 4 of the fields in the returned JSON customer have to be edited 4) JSON then needs to be used to create "Parameters" to PUT/POST back to the API.

Here's what I've done so far:

var existingCustomer = NSMutableDictionary()

...Function to acquire JSON using Alamofire...

var json = JSON(response!)
let d = json["Customer"]["Customer"].dictionaryValue

for (k, v) in d {
    if let value = v.string {
        self.existingCustomer[k] = value
    }
    //CHECK FOR OTHER TYPES
}

This works to make the dictionary look similar to the JSON, however I am concerned about the multi-dimensional aspect of the Customer JSON. I am not sure that value , once checked for being a dictionaryObject will be keep it's K,V relationship. I haven't tested yet though.

Once I get the existingCustomer Dictionary complete, I can then iterate through the entries to create the params to POST/PUT, however, again, they need to retain their KV relationship.

The params generally look like:

var params = [
    "firstName":"John",
    "lastName":"Appleseed",
    "photos": [
        "url":"www.website.com",
        "width":1024,
        "height":768
    ],
    "addresses": [
        "shippingAddress": [
            "street":"123 Test Road"
        ],
        "homeAddress": [
            "street":"456 Test Crescent"
        ]
    ],
    "phone":"555-555-5555"
]

Only much, much longer. There's something like 200 KVs

Using @GoodByeStackOverflow's Aldwych repository, I was able to get this solved fairly easily. I was able to directly modify a cloned version of the JSON object and then send it back to the API server as an NSDictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM