JSON creation in objective c, invalid JSON
I am creating a JSON
to be sent in service on checking online its showing error:
Error: Parse error on line 1: [{ "SAHExpertCode" --^ Expecting 'STRING', '}', got 'undefined' My JSON is [{"SAHExpertCode" : "", "ShiftType" : "AM", "LocFunId" : "CLT0004218", "SAHQualCode" : "CA" }] Please tell me what's wrong and how to correct it.First i am making JSON filterString = [{ "SAHExpertCode" : "", "ShiftType" : "AM", "LocFunId" : "CLT0004218","SAHQualCode" : "CA" }] on checking found it is correct then creating a dictionary NSDictionary*dictData=@{@"MbrId":[USER_DEFAULTS valueForKey:@"MemberId"],@"StrFilter":[NSString stringWithFormat:@"%@",filterString],@"shiftCrtlNos":shftCntrlNmbrs}; NSMutableArray *finalArray = [[NSMutableArray alloc]init]; [finalArray addObject:dictData]; NSString *finalString =[self ConvertArrayToJsonData:finalArray];finalString = [finalString stringByReplacingOccurrencesOfString:@"n" withString:@""]; finalString = [finalString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];after creation of final string it is generating symbol for JSON Conversion my code is -(NSString *)ConvertArrayToJsonData:(NSMutableArray *)array{ NSError error; NSData jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; NSString *JSONString; if (!jsonData) { NSLog(@"error :%@",error); } else {JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; // NSLog(@"jsonstring:%@",JSONString); } return JSONString; } //i need JSON like [ { "StrFilter" : "[ { "SAHExpertCode" : "", "ShiftType" : "PM", "LocFunId" : "CLT0004218", "SAHQualCode" : "CA" }]", "MbrId" : "MBR0000035", "shiftCrtlNos" : "0080013526,0080014697" }] also tell me how to remove from String
i replaced the unwanted symbols by doing finalString = [finalString stringByReplacingOccurrencesOfString:@"" withString:@""]; in the JSON string.
I suggest you go to www.json.org and look at the correct formatting of JSON data. And the easiest way to get correctly formatted JSON is to create an array or dictionary that you want to convert to JSON, and use NSJSONSerialization to do the job.
Just use default NSJSONSerialization method of iOS
in below example i have a "postMenuArray" which I'm converting in JSON.
NSData * postMenuSerial = [NSJSONSerialization dataWithJSONObject:postMenuArray options:0 error:nil];
NSString *Menujson = [[NSString alloc] initWithBytes:[postMenuSerial bytes] length:[postMenuSerial length] encoding:NSUTF8StringEncoding];
Here I got JSON response
Menujson = [Menujson stringByReplacingOccurrencesOfString:@" "withString:@""];
Lastly I remove all the spacing .
Still facing issue try this
Menujson = [Menujson stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
链接地址: http://www.djcxy.com/p/68342.html
上一篇: 问问每一位优秀的Java / Java EE开发人员应该能够回答?
下一篇: 在目标c中创建JSON,无效的JSON