1

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

我有这些价值观:

{"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.";
    };
}

我总是遇到同样的错误

谁能让我知道我的实施有什么问题?

4

1 回答 1

2

我想这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 值合并为一行,这只是为了清楚起见。

于 2013-10-20T19:17:12.200 回答