douhuijun3776 2011-12-24 00:57
浏览 33
已采纳

NSObject到json?

I want to convert personArray to a JSON string, and send a request to the server.

I tried something like the following code:

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

The server receives the following data:

{ \"\"name\": \"Tom\"}

The server code is this:

$json = $_POST['json_key'];
echo $json;
$json = json_decode($json, true);
echo $json; // prints nothing

Is there any way to remove the slash, or a prettier solution for converting the object to JSON?

  • 写回答

4条回答 默认 最新

  • dongyi6269 2011-12-24 02:52
    关注

    To be sure that the JSON representation is being generated properly, use a general purpose JSON generator (such as Stig Brautaset's JSON Framewark or yajl-objc) rather than ad hoc conversion.

    JSON Framework:

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

    See also:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系