使用jackson在json中发送一个字节数组

编程入门 行业动态 更新时间:2024-10-11 13:29:10
本文介绍了使用jackson在json中发送一个字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想形成一个带有两个字段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中发送一个字节数组

本文发布于:2023-11-07 15:57:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1566870.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字节   jackson   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!