php - NSObject 到 json?

标签 php iphone objective-c ios json

我想将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 Framewarkyajl-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/

相关文章:

php - PDO:无法传递变量进行准备

iphone 地址簿 - 在 ABAddressBookGetPersonWithRecordID 中获取空项目

iphone - 在应用程序内创建的文件的pathForResource

ios - 解析 rss 提要并将字符串附加到链接 - objective-c

php - 如何用 PHP 编写文件上传测试?

javascript - 如何在 Laravel 5.4 中使用 BelongsToMany 关系过滤搜索?

php - 如果数据库中的值未支付或为 0(二进制),如何将颜色更改为红色?

iphone - iOS - 将字符串转换为非 en-GB 语言环境 NSDate 返回 nil

iphone - NSFetchedResultsController 的部分名称与托管对象值不匹配

ios - 我还需要什么才能将变量保存到光盘中?