Sending a byte array in json using jackson

前端 未结 3 1441
不思量自难忘°
不思量自难忘° 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:58

    You can write your own CustomSerializer like this one:

    public class ByteArraySerializer extends JsonSerializer {
    
    @Override
    public void serialize(byte[] bytes, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeStartArray();
    
        for (byte b : bytes) {
            jgen.writeNumber(unsignedToBytes(b));
        }
    
        jgen.writeEndArray();
    
    }
    
    private static int unsignedToBytes(byte b) {
        return b & 0xFF;
      }
    
    }
    

    This one returns an unsigned byte array representation instead of a Base64 string.

    How to use it with your POJO:

    public class YourPojo {
    
        @JsonProperty("mimetype")
        private String mimetype;
        @JsonProperty("value")
        private byte[] value;
    
    
    
        public String getMimetype() { return this.mimetype; }
        public void setMimetype(String mimetype) { this.mimetype = mimetype; }
    
        @JsonSerialize(using= com.example.yourapp.ByteArraySerializer.class)
        public byte[] getValue() { return this.value; }
        public void setValue(String value) { this.value = value; }
    
    
    }
    

    And here is an example of it's output:

    {
        "mimetype": "text/plain",
        "value": [
            81,
            109,
            70,
            122,
            90,
            83,
            65,
            50,
            78,
            67,
            66,
            84,
            100,
            72,
            74,
            108,
            89,
            87,
            48,
            61
        ]
    }
    

    P.S.: This serializer is a mix of some answers that I found on StackOverflow.

提交回复
热议问题