1

プロジェクトで 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);
}

以下は、Jackson を使用して JSON ドキュメントを作成し、ObjectMapper を使用してドキュメントをシリアル化し、Messagepack も使用する私の Value クラスです。

@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 を使用していますが、そのようにする必要があります..

4

1 に答える 1