How to Update a Value in a Nested Dictionary Given Path Fragment in Swift

How to update a value in a nested dictionary given path fragment in Swift?

Note that var d: [String: Any] = data[first] as! [String: Any] makes a copy of data[first] and not a reference to it like & and inout. So, when addAt(pathFrag: &pathFrag, string: string, data: &d) is called, only d is changed. To make this change reflect on the original data[first], you have to assign d back to data[first].

Do this:

var dict: [String: Any] = ["channel": ["item": ["title": 1111]]]
var pathFrag = ["channel", "item", "title"]

func addAt(pathFrag: inout [String], data: inout [String: Any]) {
if let first = pathFrag.first {
if let item = data[first] {
pathFrag.remove(at: 0)
if !pathFrag.isEmpty {
var d: [String: Any] = data[first] as! [String: Any]
addAt(pathFrag: &pathFrag, data: &d)
data[first] = d
} else {
data[first] = 123
}
}
}
}


addAt(pathFrag: &pathFrag, data: &dict)
print(dict)

Posting JSON data using AFNetworking 2.0

after searching docs and trying out some codes I got following as an example

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];


NSDictionary *params = @ {@"user" :txtUserName, @"pwd" :txtPwd };


[manager POST:URL_SIGNIN parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"JSON: %@", responseObject);
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

Also don't forget to set response header type in the server script as Application/json.

Decode nested JSON arrays and dictionaries in Swift using Structs with JSONserialization

The JSON you provided seems to be valid. Modify your Book model and the decoding part as the following.

Model:

struct Book: Codable {
let title, author: String
}

Decoding:

let task = session.dataTask(with: url) { data, response, error in
if let data = data, error == nil {
DispatchQueue.main.async {
do {
let mybooks = try JSONDecoder().decode(BooksReturned.self, from: data)
print(mybooks)
}
} catch {
print(error.localizedDescription)
print(error)
}
}
} else {
// Failure
}
task.resume()


Related Topics



Leave a reply



Submit