如何使用Messagepack序列化JSON文档(找不到类java.lang.Object的模板)?

时间:2013-09-15 06:33:48

标签: java json serialization jackson messagepack

我打算在我们的项目中使用Messagepack。目前,我们在项目中使用JSON,我们正在将序列化JSON文档编写到Cassandra中。现在我们正在考虑使用Messagepack,这是一种有效的二进制序列化格式。

我试图找到一个很好的例子,它告诉我在JSON文档上使用Messagepack但我还是找不到它。

下面是我的主类代码,它将使用Value类使用Jackson制作JSON文档,然后使用ObjectMapper序列化JSON。

public static void main(String[] args) {

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("id", 123);
    properties.put("test", 200);
    properties.put("marks", 100);

    Value val = new Value();
    val.setProperties(properties);

    MessagePack msgpack = new MessagePack();
    // Serialize
    byte[] raw = msgpack.write(av);

    System.out.println(raw);

            // deserialize
    Value actual = new MessagePack().read(raw, Value.class);

    System.out.println(actual);
}

下面是我的Value类,它使用Jackson制作一个JSON文档,并使用ObjectMapper来序列化文档并使用Messagepack。

@JsonPropertyOrder(value = { "v" })
@Message
public class Value {

    private Map<String, Object> properties;

    /**
     * Default constructor.
     */
    @JsonCreator
    public Value() {
        properties = new HashMap<String, Object>();
    }


    /**
     * Gets the properties of this attribute value.
     * @return the properties of this attribute value.
     */
    @JsonProperty("v")
    public Map<String, Object> getProperties() {
        return properties;
    }

    /**
     * Sets the properties of this attribute value.
     * @param v the properties of this attribute value to set
     */
    @JsonProperty("v")
    public void setProperties(Map<String, Object> v) {
        properties = v;
    }


    @Override
    public String toString() {
        try {
            return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);
        } catch (Exception e) {
            // log exception
        }

        return ToStringBuilder.reflectionToString(this);
    }    
}

但是,我不确定如何在这个JSON文档上使用Messagepack?谁能给我一些这方面的例子?

但我想,让我们尝试一下这个,每当我在上面的代码中尝试使用Messagepack时这样做 -

    MessagePack msgpack = new MessagePack();
    // Serialize
    byte[] raw = msgpack.write(av);

我总是得到如下的例外情况 -

Exception in thread "main" org.msgpack.MessageTypeException: Cannot find template for class java.lang.Object class.  Try to add @Message annotation to the class or call MessagePack.register(Type).

我相信MessagePack不允许用户序列化java.lang.Object类型的变量,但在我的情况下,不可能将属性类型替换为某些原始类型。

我在HashMap中使用Object,我需要它就像那样..

1 个答案:

答案 0 :(得分:0)

您考虑使用Smile而不是尝试MessagePack,这是有效的,100%JSON API兼容的二进制数据格式。它应该匹配或超过MessagePack速度,并产生稍微更紧凑的输出。杰克逊已经实施:

https://github.com/FasterXML/jackson-dataformat-smile

将使用对象格式“正常工作”。所以而不是:

String json = new ObjectMapper().writeValueAsString(value);

你会用

byte[] smileEncoded = new ObjectMapper(new SmileFactory()).writeValueAsBytes(value);

所有Jackson代码的工作方式与JSON类似,包括JAX-RS提供程序,数据类型(Guava,Joda,Hibernate等)等。因此,您不会失去JSON的便利性(除了像所有二进制格式一样,Smile不像JSON那样可读),但是可以获得存储和性能效率。