我正在尝试使用 JSON 将图像发送到服务器。在我设置字典以使用 NSJSONSerialization 进行编码之前,数据仍然正确:我使用的函数:
- (NSData*) getHTTPBody
{
if ([NSJSONSerialization isValidJSONObject:jsonMessage])
{
NSError * error = Nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:jsonMessage options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonData;
}
return Nil;
}
使用以下输入:
Printing description of self->jsonMessage:
{
function = addattachment;
variables = {
attachment = {
enddate = 1377475200000;
file = "/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAEKADAAQAAAABAAAAEAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAQABADAREAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRCh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msXmeCyfD5QsoVGKtBwoc6xGKmnP2fNK9HmUqqSUIVvO4I8Mcm+kfX4f8QuJeEMTw3wvlsMSsJl1fOK+ZvN1VlKEuWpeM8NSozSclb35JqLu5On/9k=";
filename = "photo.jpg";
label = "Bhhhb ";
startdate = 1377475200000;
};
};
}
这似乎是正确的。事实上,我已经测试了 Base64 字符串并将其转换回在线解码器上,它完美无缺。
无论如何,生成了 JSON NSData 对象。出于测试目的,我将其转换回 NSString。这是结果:
Printing description of jsonString:
{"variables":
{"attachment":
{"enddate":1377475200000,
"filename":"photo.jpg",
"label":"Bhhhb ",
"file":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAEKADAAQAAAABAAAAEAAAAAD\/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH\/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH\/wAARCAAQABADAREAAhEBAxEB\/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL\/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6\/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL\/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBh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W8AWh0\/IttJ2r8Q0eJpx\/wjtlENX7OI+L8V4MYbPOD8g4iwOd57mNSmsXmeCyfD5QsoVGKtBwoc6xGKmnP2fNK9HmUqqSUIVvO4I8Mcm+kfX4f8QuJeEMTw3wvlsMSsJl1fOK+ZvN1VlKEuWpeM8NSozSclb35JqLu5On\/9k=",
"startdate":1377475200000}
},
"function":"addattachment"}
原始 base64 中的所有斜杠 (/) 都被反斜杠 () 转义。因此数据已损坏。有没有让 JSONSerialization 知道不转义字符串的选项?
提前谢谢了。