我想创建JSON对象参数,例如下面。我曾在iOS 5设备上工作,并且能够使用NSJSONSerialization API实现这一目标。例如,我创建了一个泛型函数“makeJSONObject()”并使用它。
Sample Payload 1:
{
token: "kjsdfjl23kkj23kk"
entries: [
{
"title": "welcome",
"name": "myself",
"date": "2012-02-06T00:14:20Z",
},{
"title": "Hi",
"name": "martin",
"date": "2012-02-06T00:14:20Z",
}
]
}
Sample Payload 2:
{
"email" : "me@company.com",
"password" : "pswrd"
}
CODE:
NSString *jsonRequest = [appDelegate makeJSONObject:[NSArray arrayWithObjects: emailStr, passwordStr, nil] :[NSArray arrayWithObjects: @"email", @"password", nil] ];
-(NSString *) makeJSONObject :(NSArray *)objects :(NSArray *)keys
{
NSString *theBodyString = NULL;
NSDictionary *data = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
//NSLog(@"data: %@", data);
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:&writeError];
theBodyString = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
return theBodyString;
}
但是,我想现在支持4.0设备,我现在不能使用NSJSONSerialization API。我可能不得不使用SBJson或类似的东西,我猜,我不知道。有人可以帮助我如何修改上面的通用功能来使用 SBJson或一些第三方解析器类?
请帮忙!谢谢。
答案 0 :(得分:0)
NSString * jsonRequest = [NSString stringWithFormat:@“& json_data =%@”,[[NSString stringWithFormat:@“{\”listInvoice \“:{\”client_id \“:\”\“,\”date_from \ “:\” \ “\ ”DATE_TO \“:\ ”\“,\ ”INVOICE_NUMBER \“:\ ”\“,\ ”invoice_record_status \“:\ ”\“,\ ”invoice_status \“:\” \ “,”“页面\”:\“1 \”,\“per_page_record \”:\“20 \”}}“] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
答案 1 :(得分:0)
尝试使用我的NSArray / NSDictionary扩展来从这些基本数据类型构建JSON字符串。 https://github.com/H2CO3/CarbonateJSON