将字节值放入NSDictionary [iOS] [英] Putting Byte value into NSDictionary [iOS]
问题描述
我有一个post web服务,我需要以字节数组发送图像,因为我需要以JSON格式发送post参数,所以我创建了它的 NSDictionary
。我的问题是如何在 Byte
的字典中为对象分配对象,我尝试这样做,并且在创建 NSDictionary
。我也用代码解释每个步骤,以便于理解下面的问题: -
I have a post web service, where I need to send image in byte array, and as I need to send post parameters in JSON format, I have created its NSDictionary
. My issue is how can I assign object to key in dictionary for Byte
, I tried doing so and application crashes while creating NSDictionary
. I am also explaining each steps with code for easy understanding of y question below :-
这是我将图像转换为字节格式的代码: -
Here is my code for converting image to Byte format :-
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data bytes];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
所以,现在我有字节
其中包含现在我想将此对象分配给 NSDictionary
。这是代码,
So, now I have Byte
which contain image in byte array, now I want to assign this object to NSDictionary
. Here is code,
NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys:
byteData, @"photo",
nil];
现在我的应用程序在上面的行中崩溃,我在创建 dictJson
object,有什么方法可以将Byte传递给 NSDictionary
?
Now my application crashes in above line where I am creating dictJson
object, is there any way I can pass Byte to NSDictionary
?
另外,另一个问题,我怎么能 NSLog
byteData
?
Also, another question, how can I NSLog
byteData
?
请帮帮我。
提前致谢!
推荐答案
如果你真的想要将图像数据作为包含字节数字的JSON数组发送,
然后你必须手动创建数组,没有内置函数:
If you really want to sent the image data as a JSON array containing the bytes as numbers, then you have to create the array "manually", there is not built-in function:
NSData *data = ... // your image data
const unsigned char *bytes = [data bytes]; // no need to copy the data
NSUInteger length = [data length];
NSMutableArray *byteArray = [NSMutableArray array];
for (NSUInteger i = 0; i < length; i++) {
[byteArray addObject:[NSNumber numberWithUnsignedChar:bytes[i]]];
}
NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys:
byteArray, @"photo",
nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJson options:0 error:NULL];
JSON数据看起来像
The JSON data would then look like
{"photo":[byte0, byte1, byte2, ...]}
所以也许这就是服务器所期望的。但请注意,这是一种非常无效的(就空间而言)发送图像数据的方式(例如,与Base64相比)。
So perhaps that is what the server expects. But note that this is a very ineffective (in terms of space) way to send image data (compared to Base64 for example).
这篇关于将字节值放入NSDictionary [iOS]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!