Json转换问题:找到无效字符

时间:2013-07-05 12:51:41

标签: ios objective-c json

我正在将我的数组转换为json对象,然后将其发送到服务器。但是当我在服务器端获取它们时,它会显示一些无效字符。比如'\ n',& '\'。 以下是我在服务器端获得的数据示例:

('[\n  "{\\"id\\":2,\\"qrCode\\":\\"KdcUfeddHpbepeXnyiKFjcfedHp\\",\\"activity\\":\\"2\\",\\"time\\":\\"64485\\",\\"image_base64\\":\\"\\/9j\\/4AAQSkZJRgABAQAA"}"\n]');

但它应该如下所示:

('[{"id":2,"qrCode":"KdcUfeddHpbepeXnyiKFjcfedHp","activity":2,"time":1372757846,"image_base64":"AA\\u003d\\u003d\\n"}]');

这是代码:

-(void)setOflynData2JsonFormat{

if (!([self.getOfflineData count] == 0)) {

    NSArray *array = [self getOfflineData];

    for (int i = 0; i<[array count]; i++) {

        uniqueId++;

        NSNumber *uId = [NSNumber numberWithInt:uniqueId];

        OfflineTableObject *offObj = [array objectAtIndex:i];

        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

        [dict setValue:uId forKey:@"id"];
        [dict setValue:offObj.qrCode forKey:@"qrCode"];
        [dict setValue:offObj.offlineStatus forKey:@"activity"];
        [dict setValue:offObj.time forKey:@"time"];
        [dict setValue:offObj.imageData forKey:@"image_base64"];

        SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];

        NSString *singleJsonString = [jsonWriter stringWithObject:dict];

        NSLog(@"Json string : %@",singleJsonString);

        arrayOfJsonString = [[NSMutableArray alloc]init];

        [arrayOfJsonString addObject:singleJsonString];

    }

    NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];

    NSString *jsonString = [[NSString alloc] initWithData:jsonDataFromArray encoding:NSUTF8StringEncoding];

    NSLog(@"jsonData as string:\n%@", jsonString);

    int check = [obj sendOfflynData2Server:jsonString];

}

}

那么,问题出在哪里?事先要求帮助。

1 个答案:

答案 0 :(得分:2)

问题是您要将数据翻译成JSON两次。

您首先使用

将所有词汇翻译成json
NSString *singleJsonString = [jsonWriter stringWithObject:dict];

将它们添加到数组中,然后使用

将数组重新转换为JSON
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];

因此,它不是产生预期的JSON输出,而是序列化一个JSON字符串数组,因此可以避免混乱。

相反,您应该将您的dicts添加到数组中,然后序列化整个事物:

arrayOfJsonString = [[NSMutableArray alloc]init];
for (int i = 0; i<[array count]; i++) {

    // snip

    [arrayOfJsonString addObject:dict];

}

NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];