Json::Serialized 不使用 proc 中的默认值

问题描述 投票:0回答:1

我试图为生成的结构体属性提供默认值。 但是反序列化时,该值仍然为空。

游乐场

require "json"

struct A
  include JSON::Serializable

  property first_seen : Time { Time.utc }
  property count : Int64 = 1
  def initialize(@first_seen : Time , count)
    @count = count.to_i64
  end
end

a = A.from_json("{}")

pp a
# A(@count=1, @first_seen=nil)
puts typeof(a.first_seen) 
# Time
puts  A.from_json("{}").to_json
# {"count":1}

我想会发生这种情况,因为默认值在编译时是未知的。 我有一个解决办法,使用

after_initialize

我希望序列化使用默认值,或者反序列化执行过程来获取默认值。

除了使用

after_initialize
还有其他方法吗?

serialization deserialization default-value crystal-lang
1个回答
0
投票

使用块来初始化

first_seen
是一个坏主意。 可以直接写:
property first_seen : Time = Time.utc
:

require "json"

struct A
  include JSON::Serializable

  property first_seen : Time = Time.utc
  property count : Int64 = 1
  def initialize(@first_seen : Time , count)
    @count = count.to_i64
  end
end

来自文档

如果为宏提供了一个块,则会使用一个变量生成一个属性,该变量使用该块的内容进行延迟初始化

© www.soinside.com 2019 - 2024. All rights reserved.