使用NSJSONSerializer iOS发布HTTP JSON请求 [英] Posting http JSON request using NSJSONSerializer iOS

查看:101
本文介绍了使用NSJSONSerializer iOS发布HTTP JSON请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

在我的.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}]";
}

这不是正确的格式. 我要这样:

This is not in correct format. I want to make it like this:

[{"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}

注意:我的网络服务返回的是正确的json格式.

Note: My web service is returning proper json format.

要实现这一目标,我还需要做些其他事情.请提出建议.

What additional things I need to do to achieve this.Please suggest.

推荐答案

您说您的Web服务返回正确的JSON,但显然不是.您应该与您的Web服务开发人员联系,并找出他们为什么返回格式错误的JSON.简而言之,除非您执行某些字符串提取(ugh)操作,否则您从Web服务中获得的收益不能被解析为JSON.

You say your web service is returning proper JSON, but clearly it's not. You should talk to your web services developer and find out why they're returning malformed JSON. Simply put, what your getting back from your web service cannot be parsed as JSON--unless you do some string extraction (ugh).

考虑使用格式更好的响应数据:

Consider your response data, better formatted:

{

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
        }
    ]
    ";

}

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

First, convert your data response to a string:

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

然后您需要将其从顶部剥离:

Then you need to strip this off this the top:

{
    d = "

这是从底部开始的

    ";

}

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

Then you can replace all of the escaped quotes using this code:

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

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

At that point, your string should be parsable JSON like this:

[
 {
   "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
 }
]

因此您可以执行以下操作:

so you can do this:

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

现在object应该将包含两个记录的数组保存为字典.

Now object should hold your array containing your two records as dictionaries.

但是,如果是我,我会回去给Web服务开发人员,要求他们修复发送给您的响应.您不必处理所有这些字符串提取废话.

If it were me, though, I would go back to the web services developer and demand they fix the response they're sending you. You shouldn't have to deal with all of this string extraction nonsense.

这篇关于使用NSJSONSerializer iOS发布HTTP JSON请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆