Base.serialize
和Base.deserialize
的默认实现为整个给定对象执行序列化/反序列化。
排除某个字段被序列化并仍能正确反序列化的正确方法是什么?
这是一个简化的代码示例:
# The target struct
struct Foo
x::Int
y::Union{Int, Void} #we do not want to serialize this field
end
foo1 = Foo(1,2)
# Serialization
write_iob = IOBuffer()
serialize(write_iob, foo1)
seekstart(write_iob)
content = read(write_iob)
# Deserialization
read_iob = IOBuffer(content)
foo2 = deserialize(read_iob)
@show foo1
@show foo2
上述代码的输出是:
foo1 = Foo(1, 2)
foo2 = Foo(1, 2)
期望的结果应该是:
foo1 = Foo(1, 2)
foo2 = Foo(1, nothing)
在此,我假设我们可以为缺失的字段定义默认值,例如,在上面的输出中nothing
为y
。
答案 0 :(得分:0)
在我当前版本的Julia(0.6.2)中深入研究序列化/反序列化的实现之后,我找到了一个解决方案。以下是问题中示例的解决方案:
# Custom Serialization of a Foo instance
function Base.Serializer.serialize(s::AbstractSerializer, instance::Foo)
Base.Serializer.writetag(s.io, Base.Serializer.OBJECT_TAG)
Base.Serializer.serialize(s, Foo)
Base.Serializer.serialize(s, instance.x)
end
# Custom Deserialization of a Foo instance
function Base.Serializer.deserialize(s::AbstractSerializer, ::Type{Foo})
x = Base.Serializer.deserialize(s)
Foo(x,nothing)
end
现在,如果再次运行测试代码:
# The target struct
struct Foo
x::Int
y::Union{Int, Void} #we do not want to serialize this field
end
foo1 = Foo(1,2)
# Serialization
write_iob = IOBuffer()
serialize(write_iob, foo1)
seekstart(write_iob)
content = read(write_iob)
# Deserialization
read_iob = IOBuffer(content)
foo2 = deserialize(read_iob)
@show foo1
@show foo2
测试代码输出:
foo1 = Foo(1, 2)
foo2 = Foo(1, nothing)
我应该提到上述解决方案取决于当前序列化/反序列化的实现(在Julia 0.6.2中),并且不能保证其未来的稳定性。因此,我仍然会留意寻找更好的解决方案。