问题描述
我正在从格式如下的网址中检索JSON数据:
I am retrieving JSON data from a URL that is formatted like so:
{"zoneresponse":
{"tasks":
[{"datafield1":"datafor1",
"datafield2":"datafor2",
"datafield3":"datafor3",...
}]
}}
我无法控制结构,因为它来自私有API。
I have no control over the structure as it is from a private API.
如何在现有对象的选定数据字段中插入数据?
我试过这个:
self.responseData = [NSMutableData data];
//testingURL is the api address to the specific object in tasks
NSURL *url = [NSURL URLWithString:testingURL];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[[[params objectForKey:@"zoneresponse"] objectForKey:@"tasks"] setValue:@"HelloWorld" forKey:@"datafield1"];
//HAVE TRIED setObject: @"" objectForKey: @"" as well
//*****PARAMS IS EMPTY WHEN PRINTED IN NSLog WHICH IS PART OF THE ISSUE - SETTING VALUE DOES NOT WORK
NSError * error = nil;
NSLog(@"Params is %@", params);
NSData *requestdata = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSMutableURLRequest *request;
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [requestdata length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:requestdata];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn) {
NSLog(@"Connection Successful, connection is: %@", conn);
} else {
NSLog(@"Connection could not be made");
}
正在建立连接但打印时字典参数为空(setValue)没有显示)并且没有在我选择的字段中输入任何数据。
The connection is being made but the dictionary params is empty when printed (the setValue is not displaying) and is not entering any data into the field I select.
我检查了这些链接,但没有解释是否会插入到正确的字段中并暗示它将创建一个新对象而不是更新现有对象。
I have checked these links but nothing explains whether it will insert into the right field and implies it will create a new object rather than update the existing one.
委托方法
//any time a piece of data is received we will append it to the responseData object
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
NSError *jsonError;
id responseDict =
[NSJSONSerialization JSONObjectWithData:self.responseData
options:NSJSONReadingAllowFragments
error:&jsonError];
NSLog(@"Did Receive data %@", responseDict);
}
//if there is some sort of error, you can print the error or put in some other handling here, possibly even try again but you will risk an infinite loop then unless you impose some sort of limit
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// Clear the activeDownload property to allow later attempts
self.responseData = nil;
NSLog(@"Did NOT receive data ");
}
//connection has finished, the requestData object should contain the entirety of the response at this point
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *jsonError;
id responseDict =
[NSJSONSerialization JSONObjectWithData:self.responseData
options:NSJSONReadingAllowFragments
error:&jsonError];
if(responseDict)
{
NSLog(@"%@", responseDict);
}
else
{
NSLog(@"%@", [jsonError description]);
}
//clear out our response buffer for future requests
self.responseData = nil;
}
此处的第一种方法表明收到的数据为已接收数据(null) ),连接没有错误,但是最终方法打印错误消息JSON文本没有以数组或对象开头,并且选项允许未设置片段。这是可以理解的,因为没有数据或对象被发送。
The first method here states that data was received with "Did Receive data (null)", there is no error with connection however the final method prints the error message "JSON text did not start with array or object and option to allow fragments not set.", which is understandable because there is no data or object being sent.
如何将数据插入现有对象的选定字段?
推荐答案
你做错了:
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[[[params objectForKey:@"zoneresponse"] objectForKey:@"tasks"] setValue:@"HelloWorld" forKey:@"datafield1"];
你的参数
是空字典而没有对象将以 [params objectForKey:@zoneresponse]
返回。
Your params
is empty dictionary and no object will be returned with [params objectForKey:@"zoneresponse"]
.
试试这个:
NSMutableDictionary *params = [NSMutableDictionary new];
params[@"zoneresponse"] = @{@"tasks": @{@"datafield1": @"HelloWorld"}};
这将起作用但对象为 @任务
将是不可变的。要将另一个对象添加到任务
字典,我们需要使其变为可变:
This will work but object for key @"tasks"
will be immutable. To add another objects to tasks
dictionary we need to make it mutable:
NSMutableDictionary *params = [NSMutableDictionary new];
NSMutableDictionary *tasks = [NSMutableDictionary new];
params[@"zoneresponse"] = @{@"tasks": tasks};
params[@"zoneresponse"][@"tasks"][@"datafield1"] = @"HelloWorld";
或
NSMutableDictionary *params = [NSMutableDictionary new];
params[@"zoneresponse"] = @{@"tasks": [@{@"datafield1": @"HelloWorld"} mutableCopy]};
然后你可以在任务中添加另一个对象
:
params[@"zoneresponse"][@"tasks"][@"datafield2"] = @"HelloWorld2";
params[@"zoneresponse"][@"tasks"][@"datafield3"] = @"HelloWorld3";
我认为我的回答会为你的字典操作带来一些清晰度。
I think my answer will bring some clarity to operations with dictionaries for you.
这篇关于将JSON数据POST到现有对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!