我想要创建一个包含两个字段mimetype和value的JSON。其中value字段应该将字节数组作为其值。
{
"mimetype":"text/plain",
"value":"dasdsaAssadsadasd212sadasd"//this value is of type byte[]
}
我该如何完成这个任务?
目前我正在使用toString()
方法将字节数组转换为字符串并形成JSON。
byte[]
转换为Base64编码的字符串并进行相互转换。JsonParser
和JsonGenerator
都具有二进制访问方法(writeBinary、readBinary),以在JSON令牌流的级别上执行相同的操作。public class Message {
public String mimetype;
public byte[] value;
}
要创建JSON,可以执行以下操作:
Message msg = ...;
String jsonStr = new ObjectMapper().writeValueAsString(msg);
或者更常见的写法是:
OutputStream out = ...;
new ObjectMapper().writeValue(out, msg);
你可以像这样编写自己的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;
}
}
这个函数返回一个无符号字节数组的表示,而不是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; }
}
以下是其输出的示例:
{
"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.:此序列化程序是我在StackOverflow上找到的答案的混合体。
byte[]
字段的POJO,则可以。其他类型的数据使用不同的转换器(例如查询参数)。 - StaxManreadBinaryValue
函数期望二进制数据以 base64 编码(标准 JSON)的形式传入。但是在实际情况中,我们可能会遇到非标准的 JSON 文档,其中包含二进制数据。 - bric3