0

我正在将我的数组转换为 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];

}

}

那么,问题出在哪里?提前寻求帮助。

4

1 回答 1

2

问题是您将数据转换为 JSON 两次。

您首先将所有 dicts 转换为 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];
于 2013-07-05T13:19:29.030 回答