Sending a byte array in json using jackson

前端 未结 3 1439
不思量自难忘°
不思量自难忘° 2020-12-08 13:52

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\":         


        
3条回答
  •  鱼传尺愫
    2020-12-08 14:35

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

    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.

    For automatic approach, consider POJO like:

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

    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);
    

提交回复
热议问题