我想将personArray
转换为JSON字符串,并向服务器发送请求。
我试过类似下面的代码:
@interface Person : NSObject {
NSString *name;
int registered;
}
+ (NSMutableArray *) select;
NSMutableArray *personArray = [Person select];
NSString *json = @"{ \"";//TODO
for (int i =0 ;i < [personArray count]; i++) {
Person *temp = [Person objectAtIndex:i];
[json stringByAppendingFormat:[NSString stringWithFormat:@"\"name\": \"%@\"", temp.name]
}
json = [json stringByAppendingFormat:[NSString stringWithFormat:@"} \""]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[global userID] forKey:@"user_id"];
[request setPostValue:json forKey:@"json_key"];
[request addRequestHeader:@"Content-type" value:@"application/json"];
[request startSynchronous];
服务器收到以下数据:
{ \"\"name\": \"Tom\"}
服务器代码是这样的:
$json = $_POST['json_key'];
echo $json;
$json = json_decode($json, true);
echo $json; // prints nothing
有什么方法可以删除斜杠,或者有更漂亮的解决方案来将对象转换为 JSON 吗?
最佳答案
为确保正确生成 JSON 表示,请使用通用 JSON 生成器(例如 Stig Brautaset 的 JSON Framewark 或 yajl-objc )而不是临时转换。
JSON 框架:
@interface Person(SBJson)
-(id)proxyForJson;
@end
@implementation Person(SBJson)
-(id)proxyForJson {
return [NSDictionary dictionaryWithObjectsAndKeys:
name,@"name",
[NSNumber numberWithInt:registered],@"registered",
nil];
}
@end
...
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[[Person select] JSONRepresentation] forKey:@"json_key"];
yajl-objc:
@interface Person(YAJL)
-(id)JSON;
@end
@implementation Person(YAJL)
-(id)JSON {
return [NSDictionary dictionaryWithObjectsAndKeys:
name,@"name",
[NSNumber numberWithInt:registered],@"registered",
nil];
}
@end
...
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[[Person select] yajl_JSONString] forKey:@"json_key"];
另见:
关于php - NSObject 到 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8621954/