序列化固定大小的映射到CBOR [英] Serialize fixed size Map to CBOR
问题描述
我有以下JSON:
[
{
2: {
"c": true
}
},
{
3: {
"p": 10
}
}
]
我想转换为CBOR格式. 根据cbor.me,我有以下输出:
That I would like to convert to CBOR format. Accordingly to cbor.me I have the following output:
82A102A16163F5A103A161700A
82A102A16163F5A103A161700A
但是,当使用Jackson Binary CBOR串行器时,我有以下输出:
But, when using Jackson Binary CBOR Serializer, I have the following output:
82BF02BF6163F5FFFFBF03BF61700AFFFF
82BF02BF6163F5FFFFBF03BF61700AFFFF
这没错,但没有进行优化...我实际上增加了4个不必要的字节.
Which is not wrong, but not optimized... I have an extra 4 unnecessary bytes added to what it can really be.
然后我尝试手动序列化JSON,但结果相同:
I've then tried to manually serialize the JSON but same result:
@Override
public void serialize(Request value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartArray(value.getDataList().size());
for (Data data : value.getDataList()) {
jgen.writeStartObject(new Map[1]);
jgen.writeFieldId(data.getItem());
jgen.writeStartObject();
if (data.getObject().getC() != null) {
jgen.writeBooleanField("c", data.getObject().getC());
}
if (data.getObject().getP() != null) {
jgen.writeNumberField("p", data.getObject().getP());
}
jgen.writeEndObject();
jgen.writeEndObject();
}
jgen.writeEndArray();
}
这是Jackson Binary格式库的错误,还是我缺少ObjectMapper的某些配置属性?
Is this a bug with Jackson Binary format library or am I missing some configuration properties from the ObjectMapper?
EDIT: This seems to be a known issue: https://github.com/FasterXML/jackson-dataformats-binary/issues/3
推荐答案
使用版本2.9.4
可以在CBORGenerator
类中使用以下方法:public final void writeStartObject(int elementsToWrite)
By using version 2.9.4
the following method is available in the CBORGenerator
class: public final void writeStartObject(int elementsToWrite)
@Override
public void serialize(Request value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartArray(value.getDataList().size());
for (Data data : value.getDataList()) {
((CBORGenerator) jgen).writeStartObject(1);
jgen.writeFieldId(data.getItem());
((CBORGenerator) jgen).writeStartObject(1);
if (data.getObject().getC() != null) {
jgen.writeBooleanField("c", data.getObject().getC());
}
if (data.getObject().getP() != null) {
jgen.writeNumberField("p", data.getObject().getP());
}
jgen.writeEndObject();
jgen.writeEndObject();
}
jgen.writeEndArray();
}
我有以下输出:
82A102A16163F5A103A161700A
82A102A16163F5A103A161700A
这篇关于序列化固定大小的映射到CBOR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!