protostuff deserialize empty collection null

protostuff反序列化空集合爲null。

問題描述

有一個class A,含一個集合字段。創建對象時,如果集合字段賦值empty(不是null),那麼反序列化後該字段變爲null。

public class A {
    List<Object> lo;
    String name;
}

A a = new A();
a.setLo(new ArrarList<>());
a.setName("a");

var b = serialize(a);
var c = deserialize(b);
// c.lo is null

原因分析

這是因爲protostuff默認不序列collection本身,只序列化collection裏面的元素。

解決1:

private List<String> foo = new ArrayList<String>();

解決2:

You can use this scheme,an empty List after deserialization


IdStrategy strategy = new DefaultIdStrategy(IdStrategy.DEFAULT_FLAGS 
    | IdStrategy.COLLECTION_SCHEMA_ON_REPEATED_FIELDS ,null,0); 
schema = RuntimeSchema.createFrom(originClazz, strategy);

解決3:

If you are to purely use this to replace java serialization (no compatibility with protobuf), set the following system properties:

-Dprotostuff.runtime.always_use_sun_reflection_factory=true
-Dprotostuff.runtime.preserve_null_elements=true
-Dprotostuff.runtime.morph_collection_interfaces=true
-Dprotostuff.runtime.morph_map_interfaces=true
-Dprotostuff.runtime.morph_non_final_pojos=true

Reference

  1. Can not correctly deserialize empty List · Issue #219 · protostuff/protostuff (github.com)
  2. protostuff/RuntimeEnv.java at master · protostuff/protostuff (github.com)
  3. Empty ArrayList data member being deserialized back as null (google.com)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章