ios - 在 iOS 中创建 JSON 字符串

标签 ios json web-services http-post

如何在 iOS 中为 HTTP 请求创建 JSON 字符串

我有这些值(value)观:

{"name":"customer6","pass":"customer6",  "mail":"customer6@xy.com","user_roles":"5", "field_login_pin_value":{"und":[{"value":"2324"}]} }

那么如何从这些数据中生成 JSON 字符串呢?

这是我的代码:

NSArray *keys = [NSArray arrayWithObjects:@"name",@"pass",@"mail",@"user_roles",@"field_login_pin_value", nil];

NSArray *objects = [NSArray arrayWithObjects:@"customer6",@"customer6",@"customer6@xy.com",@"5",@"{\"und\":[{\"value\":\"2324\"}]", nil];

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSString *jsonString = [jsonDictionary JSONRepresentation];


NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxxxxx/register.json"]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:jsonString forHTTPHeaderField:@"json"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];

nsconnection= [[NSURLConnection alloc] initWithRequest:request delegate:self];

当我点击网络服务请求时,我得到以下响应:

 "form_errors" =     {
        "field_login_pin_value][und][0][value" = "PIN value field is required.";
    };
}

我总是得到同样的错误

任何人都可以让我知道我的实现有什么问题吗?

最佳答案

我想 JSONRepresentation 正在将 "{\"und\":[{\"value\":\"2324\"}]" 格式化为它是文字字符串,而不是字典中数组中字典中的值。你应该制作整个 dict-array-dict 结构。如果您使用数组和字典文字,这一切都会更容易:

NSDictionary *jsonDictionary = @{
    @"name" : @"customer6",
    @"pass" : @"customer6",
    @"mail" : @"customer6@xy.com",

    @"user_roles" : @"5",

    @"field_login_pin_value" : @{
        @"und":@[
            @{
                @"value" : @"2324"
            }
        ]
    }
};

当然,您可以将 pin_value 值合并到一行,这只是为了清楚起见。

关于ios - 在 iOS 中创建 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19481538/

相关文章:

xml - Web api 应该默认返回 JSon

java - 如何在 Spring WS 中处理语法不正确的 XML?

ios - 计算出 UIView 的大小

ios - indexPath.row 给出了奇怪的值

php - 使用 SLIM3 将 PHP 数组转换为 JSON 数组并获取响应

java - 与 Mongo 的版本化对象/JSON 映射?

java - Tomcat 更新事件

c# - Unity Web 请求包装器

ios - 沿弧线放置 UICollectionViewCells (UIBezierPath)

ios - 如何禁用 UIDatePicker 中的特定日期