我想在我的app.my中JSON
格式JSON
是这样的:
{
user: {
id: 2
},
items: [
{
id: 2,
num: 3
}
]
}
我可以用这段代码制作JSON格式:
NSMutableDictionary *json = [[NSMutableDictionary alloc]init];
NSMutableDictionary *users = [[NSMutableDictionary alloc]init];
[users setObject:@"2" forKey:@"id"];
NSMutableDictionary *item = [[NSMutableDictionary alloc]init];
[item setObject:@"22" forKey:@"id"];
[item setObject:@"33" forKey:@"num"];
NSMutableArray *itemArray = [[NSMutableArray alloc]initWithObjects:item, nil];
[json setObject:users forKey:@"user"];
[json setObject:itemArray forKey:@"items"];
NSLog(@"%@",json);
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json
options:0
error:&error];
现在我想知道这是真的吗?
如果这是真的,请指导我如何使用JSON
方法将此POST
发送到网址?
此代码用于发送JSON
:
NSURL *url = [NSURL URLWithString: @"http://192.168.1.193/deliapi/order/new?token=absc"];
NSString *postLength = [NSString stringWithFormat:@"%d",[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:jsonData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
if(conn)
{
NSLog(@"Connection Successful");
}
else
{
NSLog(@"Connection could not be made");
}
答案 0 :(得分:0)
我的朋友你的代码是对的!你应该为HeaderField确定application / json:
编写此代码:
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
我希望能帮到你!!!