ios - 想要创建一个json并将其发送到url

标签 ios objective-c json

我已经使用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/

相关文章:

objective-c - iOS 低电量警告会触发哪些事件?它正在重置我的应用程序

java - 将 String 值解析为 JsonElement 会给出 MalformedJsonException

java - Talend 导入库

iphone - 使用 NSUserDefaults xcode iphone 的问题

ios - 可变高度 subview Controller 作为 UITableView 的 tableHeaderView

objective-c - 在 Cocoa 中生成一个随机的字母数字字符串

javascript - 使用javascript将base64字符串转换为图像

html - 当触发 iOS Safari 中的虚拟键盘时,它会使我的 CSS 过渡闪烁。这怎么能解决?

ios - TableView 的 UISearchController

ios - 在另一个 UIViewController 中嵌入 UIViewController View