简体   繁体   中英

Posting http JSON request using NSJSONSerializer iOS

Here is my code:

In my .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];
}

This is returning me data as:

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

Note: My web service is returning proper json format.

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

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 = "

and this from the bottom

    ";

}

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

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

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

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

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.

Trainer_ID and NumberofDays are primitive. You can't add then into NSArray as is. You should wrap them into 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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM