使用 jackson 在 json 中发送字节数组 [英] Sending a byte array in json using jackson

查看:54
本文介绍了使用 jackson 在 json 中发送字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想形成一个包含mimetype和value两个字段的JSON.value字段应该以字节数组作为其值.

I want to form a JSON with two fields mimetype and value.The value field should take byte array as its value.

{

  "mimetype":"text/plain",

  "value":"dasdsaAssadsadasd212sadasd"//this value is of type byte[]

}

我怎样才能完成这个任务?

How can I accomplish this task?

截至目前,我正在使用 toString() 方法将字节数组转换为字符串并形成 JSON.

As of now I am using toString() method to convert the byte array into String and form the JSON.

推荐答案

如果您使用 Jackson 进行 JSON 解析,它可以通过数据绑定自动将 byte[] 与 Base64 编码的字符串相互转换.

If you are using Jackson for JSON parsing, it can automatically convert byte[] to/from Base64 encoded Strings via data-binding.

或者,如果您想要低级别访问,JsonParserJsonGenerator 都有二进制访问方法(writeBinary、readBinary)在 JSON 令牌流级别执行相同操作.

Or, if you want low-level access, both JsonParser and JsonGenerator have binary access methods (writeBinary, readBinary) to do the same at level of JSON token stream.

对于自动方法,请考虑 POJO,例如:

For automatic approach, consider POJO like:

public class Message {
  public String mimetype;
  public byte[] value;
}

要创建 JSON,您可以这样做:

and to create JSON, you could do:

Message msg = ...;
String jsonStr = new ObjectMapper().writeValueAsString(msg);

或者,更常见的是用:

OutputStream out = ...;
new ObjectMapper().writeValue(out, msg);

这篇关于使用 jackson 在 json 中发送字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆