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条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题