反序列化嵌套对象结构时的Ruby YAML问题

时间:2009-10-26 09:08:38

标签: ruby serialization yaml

我有3个类具有以下关系:

战地拥有一系列团队。

BattleTeam 拥有一系列成员,以及对战场的引用。

Jaguar BattleTeam 的成员,并且引用了它。

如果我将Jaguar序列化/反序列化,最后是BattleTeam,那就没问题了。序列化/反序列化战场时会出现问题。

序列化它会产生适当的结果,但反序列化会将BattleTeam中的成员变为零。

让我告诉你:

>> j = Jaguar.new
=> #<Jaguar:0xa2221f8 @vitality=nil, @spirituality=nil, @log=nil, @name=nil>

#A battleteam might have many members:
>> t = BattleTeam.new
=> #<BattleTeam:0xa21fafc @members=[], @dead_members=[]>

#A battlefield might have many teams:
>> b = Battlefield.new
=> #<Battlefield:0xa2075d8 @teams=[]>

#Add a member to the team
>> t.add_member(j)
=> #<BattleTeam:0xa21fafc @members=[#<Jaguar:0xa2221f8 @vitality=nil, @spirituality=nil, @log=nil, @name=nil, @battle_team=#<BattleTeam:0xa21fafc ...>], dead_members[]

#Add a team to the battlefield
>> b.add_team(t)
=> #<Battlefield:0xa2075d8 @teams=[#<BattleTeam:0xa21fafc @members=[#<Jaguar:0xa2221f8 @vitality=nil, @spirituality=nil, @log=nil, @name=nil, @battle_team=#<BattleTeam:0xa21fafc ...>>], @dead_members=[], @battlefield=#<Battlefield:0xa2075d8 ...>>]>

#Serialize and deserialize the jaguar object (it works as expected):
>> YAML::load j.to_yaml
=> #<Jaguar:0xa1e3cdc @vitality=nil, @spirituality=nil, @log=nil, @name=nil, @battle_team=#<BattleTeam:0xa1e4204 @members=[#<Jaguar:0xa1e3cdc ...>], dead_members[], battlefield#<Battlefield:0xa1e4038 @teams=[#<BattleTeam:0xa1e4204 ...>]

#Serialize and deserialize the battle team object (it words as expected):
>> YAML::load t.to_yaml
=> #<BattleTeam:0xa1d0664 @members=[#<Jaguar:0xa1cfee4 @vitality=nil, @spirituality=nil, @log=nil, @name=nil, @battle_team=#<BattleTeam:0xa1d0664 ...>], dead_members[], battlefield#<Battlefield:0xa1d0470 @teams=[#<BattleTeam:0xa1d0664 ...>]

#Serialize and deserialize the battle team object
#(here the @members array is deserialized as nil, this is not expected!):
>> YAML::load b.to_yaml
=> #<Battlefield:0xa1c370c @teams=[#<BattleTeam:0xa1c33b0 @members=nil, @dead_members=[], @battlefield=#<Battlefield:0xa1c370c ...>]

>> YAML::load(b.to_yaml).teams[0].members
=> nil


#Here is the generated yaml, it looks right, the member is there:
>> puts b.to_yaml
--- &id002 !ruby/object:Battlefield 
teams: 
- &id001 !ruby/object:BattleTeam 
  battlefield: *id002
  dead_members: []

  members: 
  - !ruby/object:Jaguar 
    battle_team: *id001
    log: 
    name: 
    spirituality: 
    vitality: 
=> nil

有人知道这有什么问题吗?

1 个答案:

答案 0 :(得分:0)

我真的不太了解YAML或序列化/反序列化.. 但是看看:

把b.to_yaml ---&amp; id002!ruby / object:战场 团队: - &amp; id001!ruby / object:BattleTeam   战场:* id002   dead_members:[]

成员:    - !ruby / object:美洲虎     battle_team:* id001     日志:     名称:     灵性:     活力: =&GT;零

战场和战场怎么样:

--- &id002 !ruby/object:Battlefield 
- &id001 !ruby/object:BattleTeam 

Jaguar看起来像这样:

  - !ruby/object:Jaguar 

id似乎不见了......?