【问题标题】:How to post REST through JSON in Objective-C如何在 Objective-C 中通过 JSON 发布 REST
【发布时间】:2013-03-04 16:53:42
【问题描述】:

我的编程能力并不强,而且似乎面临着非常简单的问题。我不知道如何通过带有 json 的 REST 请求在服务器上发布数据。 必须接受的格式是

{
    "date": "2012-12-20 12:00:00",
    "address": "asd",
    "name": "asdasdasdasdasd",
    "shipping_date": "2012-12-20 12:00:00",
    "receiver_phone": "123456789",
    "customer_phone": "123456789",
    "total_price": "1234",
    "items": {
        "1": {
            "item_id": "1",
            "quantity": "1",
            "type": "1",
            "color_id": "0"
        }
    }
} 

我找到了一篇文章Post data in Objective C using Json,但无法正确格式化我的字符串。

【问题讨论】:

  • 您可以尝试使用流行的网络库,如 AFNetworking、RestKit 等。它们使这种 RESTful Web 服务变得简单。即使您不使用它们,您也可以使用所有值形成一个 NSDictionary 实例。我认为 items 的值是一个数组。然后将字典的数据post到request的postData中。
  • NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"2013-03-03 12:12:12", @"date", @"asd", @"address",[NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"item_id", @"1", @"quantity", @"1", @"type", @"0", @"color_id", nil], @ "1", nil], @"items",nil];
  • 是的。我会给你一个答案。

标签: objective-c json post


【解决方案1】:

看起来该帖子正是您想要的,减去格式位。 JSONKit is a very simple 类使用。我发现它比NSJSONSerialization 更强大。但是为此,我会缝合NSJSONSerialization

// create a dictionary with the structure you want
NSDictionary *dict = @{
    @"date":@"2012-12-20 12:00:00",
    @"address":@"asd",
    @"name":@"asdasdasdasdasd",
    @"shipping_date":@"2012-12-20 12:00:00",
    @"receiver_phone":@"123456789",
    @"customer_phone":@"123456789",
    @"total_price": @"1234",
    @"items": @{
        @"1": @{
            @"item_id": @"1",
            @"quantity": @"1",
            @"type": @"1",
            @"color_id": @"0"
        }
    }
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:nil error:&error];

if ( error ) {
    // handle accordingly
}
else if ( jsonData != nil ) {
    NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF*Encoding];
    // build request like example
}

现在您可以使用示例的其余部分了。

更新

我发现JSONKitNSJSONSerialization 强大得多,并且需要的步骤更少,但NSJSONSerialization 应该产生相同的结果,并且不需要担心混合 ARC 和非 ARC 代码。

更新 2

我建议给JSONKit 一个认真的外观,它不那么挑剔(即值可以是NSNumber 而不是NSString)。它确实需要在JSONKit.m 的构建阶段设置-fno-objc-arc 标志。

【讨论】:

  • @Asike 更新了一个更好的例子来说明如何创建你想要的数据结构。
  • 很遗憾 JSONKit 不支持 Objective-C 自动引用计数 (ARC)
  • 运行项目后。我有这个:由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“JSON 字典中的无效(非字符串)键”
  • @Asike 我的错,已修复以将所有键和值设为 NSString
【解决方案2】:

如果您创建一个字典,然后使用 NSJSONSerialization 将其转换为数据会更好。

NSDictionary *params = ...

NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:params 
                                                   options:0 
                                                     error:&error];
[request setHTTPBody:postData];

【讨论】:

    【解决方案3】:
    - (IBAction)registerclick:(id)sender
    

    {

    if (_password.text==_repassword.text)
    {
        [_errorlbl setHidden:YES];
    
    
    NSString *requstUrl=[NSString stringWithFormat:@"http://iroidtech.com/fresery/index.php?route=api/fresery/registerCustomer"];
    
     NSString *postString=[NSString stringWithFormat:@"name=asd&email=sooraj&phonenumber=8111&password=soorajsnr&type=1&facebookid=&image_path="];
       // _name.text,_email.text,_mobile.text,_password.text
    
    NSData *returnData=[[NSData alloc]init];
    
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:requstUrl]];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postString length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    resp=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
    
    
        c=[[resp valueForKey:@"status" ]objectAtIndex:0];
        b=[[resp valueForKey:@"message"]objectAtIndex:0];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多