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 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大