简体   繁体   English

使用原型对象进行序列化/反序列化

[英]Serialization/Deserialization with prototype objects

Basically I got into problem where I am not sure what to do next. 基本上我遇到了不确定下一步该怎么做的问题。 Maybe I just made my solution too complicated and there's one more simpler or I just don't see an answer. 也许我只是使我的解决方案过于复杂,而又有一个简单的解决方案,或者我只是没有找到答案。 I am developing a system where each object has a prototype parent of its own. 我正在开发一个系统,其中每个对象都有自己的原型父对象。 Prototype object has all the information that objects needs. 原型对象具有对象所需的所有信息。 During the serialization I only store properties that are different from the same property in prototype object. 在序列化期间,我仅将与同一属性不同的属性存储在原型对象中。 I do that do decrease serialized object file size. 我这样做确实减少了序列化目标文件的大小。 That seems nice, but it creates a new problem. 看起来不错,但这会带来一个新问题。

Here's an example: lets say I have a enemy character object. 这是一个例子:假设我有一个敌人角色对象。 It has name, health, inventory values, etc. During game saving process I serialize all of it, excluding values that didn't change and are the same like in prototype object. 它具有名称,运行状况,库存值等。在游戏保存过程中,我将所有序列化,不包括未更改且与原型对象相同的值。 That part is easy, but what I don't understand is how to solve my deserialization process. 这部分很简单,但是我不了解的是如何解决反序列化过程。

When I load my game back I want to deserialize objects from my save files and then - if a prototype objects exists, I want to populate deserialized objects with prototype object data. 当我重新加载游戏时,我想从保存文件中反序列化对象,然后-如果存在原型对象,我想用原型对象数据填充反序列化的对象。 The problem that I see in this case is that if character's inventory contains different items from its prototype - it will still receive those items from original blueprint object. 在这种情况下,我看到的问题是,如果角色的清单中包含与原型不同的物品,它将仍然从原始蓝图对象中接收这些物品。

How can I automate cases like that where I want to skip some values if they are already there? 我该如何自动化类似这样的情况:如果它们已经存在,我想跳过一些值? For example if health value already exists - I don't want a original value from prototype. 例如,如果健康值已经存在-我不想要原型的原始值。 Or if inventory already has items in it - I don't want to receive items from blueprint object. 或者,如果库存中已经有物品-我不想从蓝图对象接收物品。

You can do something like this: 您可以执行以下操作:

JObject o1 = JObject.Parse(@"{
  'FirstName': 'John',
  'LastName': 'Smith',
  'Enabled': false,
  'Roles': [ 'User' ]
}");
JObject o2 = JObject.Parse(@"{
  'Enabled': true,
  'Roles': [ 'User', 'Admin' ]
}");

o1.Merge(o2, new JsonMergeSettings
{
    // union array values together to avoid duplicates
    MergeArrayHandling = MergeArrayHandling.Union
});

string json = o1.ToString();
// {
//   "FirstName": "John",
//   "LastName": "Smith",
//   "Enabled": true,
//   "Roles": [
//     "User",
//     "Admin"
//   ]
// }

Copied from: http://james.newtonking.com/archive/2014/08/04/json-net-6-0-release-4-json-merge-dependency-injection 复制自: http : //james.newtonking.com/archive/2014/08/04/json-net-6-0-release-4-json-merge-dependency-injection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM