我想形成一个带有两个字段mimetype和value的JSON。值字段应该以字节数组作为其值。
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[] }如何完成此任务?
截至目前,我使用 toString()方法将字节数组转换为String并形成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.
或者,如果你想要低级访问,那么 JsonParser 和 JsonGenerator 具有二进制访问方法(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);或更常见的是用以下内容写出:
or, more commonly would write it out with:
OutputStream out = ...; new ObjectMapper().writeValue(out, msg);更多推荐
使用jackson在json中发送一个字节数组
发布评论