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

Sud*_*hin 23 json jackson

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

{

  "mimetype":"text/plain",

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

}
Run Code Online (Sandbox Code Playgroud)

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

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

Sta*_*Man 35

如果您使用Jackson进行JSON解析,它可以byte[]通过数据绑定自动转换为Base64编码的Strings.

或者,如果你想低级别的访问,双方JsonParserJsonGenerator有二进制访问方法(writeBinary,readBinary)做同样的JSON令牌流的水平.

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

public class Message {
  public String mimetype;
  public byte[] value;
}
Run Code Online (Sandbox Code Playgroud)

要创建JSON,您可以:

Message msg = ...;
String jsonStr = new ObjectMapper().writeValueAsString(msg);
Run Code Online (Sandbox Code Playgroud)

或者,更常见的是将其写出来:

OutputStream out = ...;
new ObjectMapper().writeValue(out, msg);
Run Code Online (Sandbox Code Playgroud)


Alb*_*lla 15

您可以像这样编写自己的CustomSerializer:

public class ByteArraySerializer extends JsonSerializer<byte[]> {

@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;
  }

}
Run Code Online (Sandbox Code Playgroud)

这个返回一个无符号字节数组表示而不是Base64字符串.

如何在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; }


}
Run Code Online (Sandbox Code Playgroud)

以下是它的输出示例:

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

PS:这个序列化器是我在StackOverflow上找到的一些答案的混合.


Dre*_*een 3

您可能想要使用Base64将二进制数据转换为字符串。大多数编程语言都有 Base64 编码和解码的实现。如果您想在浏览器中解码/编码,请参阅此问题