0

我想创建 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"
}

代码:

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 或一些第三方解析器类吗?

请帮忙!谢谢你。

4

2 回答 2

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

于 2012-04-30T07:37:38.477 回答
0

试试我的 NSArray/NSDictionary 扩展,从这些基本数据类型构建 JSON 字符串。 https://github.com/H2CO3/CarbonateJSON

于 2012-04-30T07:40:12.340 回答