我已经使用NSDictionary创建了一个json。这是我的代码。
NSArray *propertyNames1 = [NSArray arrayWithObjects:@"Name", @"Lat", @"Lng", nil];
NSArray *propertyValues1 = [NSArray arrayWithObjects:@"testName1", @"32.345453", @"23.5456346", nil];
NSDictionary *properties1 = [NSDictionary dictionaryWithObjects:propertyValues1 forKeys:propertyNames1];
我想将其发送到url。为此我使用了这段代码。
NSString *urlString=[NSString stringWithFormat:@"http:example.com];
NSMutableURLRequest *mrequest = [[NSMutableURLRequest alloc] init];
[mrequest setURL:[NSURL URLWithString:urlString]];
[mrequest setHTTPMethod:@"PUT"];
[mrequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSString *post =[NSString stringWithFormat:@"%@",properties1];
NSData *body = [NSData dataWithBytes: [post1 UTF8String] length:[post1 length]];
[mrequest setHTTPBody:body];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:mrequest delegate:self];
if(connection)
{
webdata = [[NSMutableData alloc] init];
}
但是它作为发布到URL中
{
“{\ n Lat”:“\” 32.345453 \“; \ n Lng = \” 23.5456346 \“; \ n名称= testName1; \ n}”
}
我需要输出为
{
{
"Lat": "32.345453"
"Lng": "23.5456346"
"Name": "testName1"
}
}
请帮我...
最佳答案
//构建一个信息对象并转换为json
NSDictionary *properties1 = [NSDictionary dictionaryWithObjects:propertyValues1 forKeys:propertyNames1];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject: properties1 options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://example.com"]];];
[request setHTTPMethod:@"PUT"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];
// print json:
NSLog(@"JSON summary: %@", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(connection)
{
webdata = [[NSMutableData alloc] init];
}
关于ios - 想要创建一个json并将其发送到url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20561110/