使用NSJSONSerializer iOS发布http JSON请求

时间:2013-02-19 15:34:19

标签: iphone ios objective-c json nsjsonserialization

这是我的代码:

在我的.m

NSArray *keys = [NSArray arrayWithObjects:@"Training_Code", @"Training_Duration",@"Training_Startdate",@"Training_Enddate",@"Trainer_ID",@"Training_Location",@"Comments",@"Keyword",@"NumberofDays", nil];
NSArray *objects = [NSArray arrayWithObjects:@"Training_Code", @"Training_Duration",@"Training_Startdate",@"Training_Enddate",@"Trainer_ID",@"Training_Location",@"Comments",@"Keyword",@"NumberofDays", nil];
NSData *jsonData;
NSString *jsonString;
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
    jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
    jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}

// Be sure to properly escape your url string.
NSURL *url1 = [NSURL URLWithString:@"http://xx.xx.xx.xxx/DeployiOSCalender/service1.asmx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: jsonData];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];

NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];

if (errorReturned) {
    // Handle error.
}
else
{
    NSError *jsonParsingError = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
}

这会将数据返回为:

{
d = "[{\"Training_Code\":\"1234      \",\"Training_Duration\":\"2hrs      \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321      \",\"Training_Duration\":\"16        \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]";
}

格式不正确。 我想这样做:

[{"Training_Code":"1234      ","Training_Duration":"2hrs      ","Training_Startdate":"14/02/2013 15:00:00","Training_Enddate":"14/02/2013 17:00:00","Trainer_ID":1,"Training_Location":"B-Wing Training room-4","Comments":"C# training","Keyword":"C#1234","NumberofDays":1},{"Training_Code":"4321      ","Training_Duration":"16        ","Training_Startdate":"17/02/2013 10:30:00","Training_Enddate":"17/02/2013 17:30:00","Trainer_ID":2,"Training_Location":"A-Wing Training Room-6","Comments":"Objective-C","Keyword":"Obj-C4321","NumberofDays":2}

注意:我的Web服务正在返回正确的json格式。

我需要做些什么才能实现这一点。请建议。

2 个答案:

答案 0 :(得分:2)

您说您的网络服务正在返回正确的JSON,但显然它不是。您应该与您的Web服务开发人员交谈,并找出他们返回格式错误的JSON的原因。简单地说,从Web服务中获取的内容无法解析为JSON - 除非您进行字符串提取(ugh)。

考虑您的回复数据,格式更好:

{

d = "
    [
        {
            \"Training_Code\":\"1234      \",
            \"Training_Duration\":\"2hrs      \",
            \"Training_Startdate\":\"14/02/2013 15:00:00\",
            \"Training_Enddate\":\"14/02/2013 17:00:00\",
            \"Trainer_ID\":1,
            \"Training_Location\":\"B-Wing Training room-4\",
            \"Comments\":\"C# training\",
            \"Keyword\":\"C#1234\",
            \"NumberofDays\":1
        },
        {
            \"Training_Code\":\"4321      \",
            \"Training_Duration\":\"16        \",
            \"Training_Startdate\":\"17/02/2013 10:30:00\",
            \"Training_Enddate\":\"17/02/2013 17:30:00\",
            \"Trainer_ID\":2,
            \"Training_Location\":\"A-Wing Training Room-6\",
            \"Comments\":\"Objective-C\",
            \"Keyword\":\"Obj-C4321\",
            \"NumberofDays\":2
        }
    ]
    ";

}

首先,将数据响应转换为字符串:

NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

然后你需要将它从顶部剥离:

{
    d = "

这是从底部

    ";

}

然后,您可以使用以下代码替换所有转义的引号:

json = [json stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];

此时,您的字符串应该是可解析的JSON,如下所示:

[
 {
   "Training_Code":"1234      ",
   "Training_Duration":"2hrs      ",
   "Training_Startdate":"14/02/2013 15:00:00",
   "Training_Enddate":"14/02/2013 17:00:00",
   "Trainer_ID":1,
   "Training_Location":"B-Wing Training room-4",
   "Comments":"C# training",
   "Keyword":"C#1234",
   "NumberofDays":1
 },
 {
   "Training_Code":"4321      ",
   "Training_Duration":"16        ",
   "Training_Startdate":"17/02/2013 10:30:00",
   "Training_Enddate":"17/02/2013 17:30:00",
   "Trainer_ID":2,
   "Training_Location":"A-Wing Training Room-6",
   "Comments":"Objective-C",
   "Keyword":"Obj-C4321",
   "NumberofDays":2
 }
]

所以你可以这样做:

id object = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];

现在object应该将包含两个记录的数组作为词典。

如果是我,我会回到网络服务开发人员并要求他们修复他们发送给你的回复。你不应该处理所有这些字符串提取废话。

答案 1 :(得分:0)

Trainer_ID和NumberofDays是原始的。你不能按原样添加到NSArray中。你应该把它们包装成NSNumber:

NSArray *objects = [NSArray arrayWithObjects:Training_Code, Training_Duration,Training_Startdate,Training_Enddate,[NSNumber numberWithInt:Trainer_ID],Training_Location,Comments,Keyword,[NSNumber numberWithInt:NumberofDays], nil];