简体   繁体   English

如何在Ruby中将字节数组转换为JSON字符串

[英]How to convert an array of bytes to JSON string in Ruby

What I am trying to achieve: 我想要达到的目标:

  1. Convert a Dictionary to NSData which contains normal text as well as an image: 将Dictionary转换为NSData,其中包含普通文本和图像:

     let payload: Dictionary<String, AnyObject> = [ "some_item": "some_value", "img": UIImagePNGRepresentation(img)! ] let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(payload) 
  2. Send this data to the server using WebSocket writeData 使用WebSocket writeData将此数据发送到服务器

  3. Parse the array of bytes to get a JSON string and save the image and send back some response. 解析字节数组以获取JSON字符串并保存图像并发送回一些响应。

I am using Rails4 as the backend and I have tried pack but it doesn't work. 我正在使用Rails4作为后端,并且尝试过pack但是不起作用。 I am not sure if this is doable or not. 我不确定这是否可行。

I know Base64 encoding will work instead of byte data, but it's a bit slower than what I would prefer. 我知道Base64编码可以代替字节数据工作,但是比我希望的慢一些。

First you need to stop using NSKeyedArchiver and instead use NSJSONSerialization .Tl his will generate actual JSON data for you that you should be able to unpack easily on the server. 首先,您需要停止使用NSKeyedArchiver ,而应使用NSJSONSerialization .Tl他将为您生成实际的JSON数据,您应该能够在服务器上轻松解压缩。

When using an image you either: 使用图像时,您可以:

  1. don't use JSON with it 不要使用JSON
  2. convert the image data into base64 and create the JSON including that text 将图像数据转换为base64并创建包含该文本的JSON
  3. use multi-part form upload with a section for the image and another for the rest of the JSON 使用多部分表单上传,其中一部分用于图像,另一部分用于JSON的其余部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM