序列化特定的私有字段



我有以下类:

public class TriGrid
{
    private List<HexTile> _hexes;
    //other private fields...
    //other public proprerties
}
我的目标是只序列化_hexes字段,所以我创建了以下ContractResolver:
internal class TriGridContractResolver : DefaultContractResolver
{
    protected override List<MemberInfo> GetSerializableMembers(Type objectType)
    {
        return new List<MemberInfo> { objectType.GetMember("_hexes", BindingFlags.NonPublic | BindingFlags.Instance)[0] };
    }
}

,当我想序列化一个TriGrid的实例时,我做:

var settings = new JsonSerializerSettings()
{
    ContractResolver = new TriGridContractResolver()
};
var json = JsonConvert.SerializeObject(someTriGrid, settings);
string strintJson = json.ToString();

,但当我检查strintJson的值总是"{}"_hexes有元素,它不是空的。如果我序列化一个特定的HexTile,它会像预期的那样工作。我哪里做错了?

不需要实现自定义DefaultContractResolver。解决方案是将[JsonProperty]放在_hexes上,[JsonIgnore]放在所有其他属性和字段上。

因为业务模型最终会改变,所以我更喜欢实现isserializable并使用。net的方式来创建纪念品(例如,一个属性包)。当您需要在运行时对对象进行版本控制时,这种方法最有效。任何你不想序列化的东西,都不要放到属性包里。

特别是,因为JSON。Net (Newtonsoft.Json)也将通过其序列化和反序列化方法来尊重它。

using System;
using System.Runtime.Serialization;
[Serializable]
public class Visitor : ISerializable
{
    private int Version;
    public string Name { get; private set; }
    public string IP { get; set: }
    public Visitor()
    {
        this.Version = 2;
    }
    public void ChangeName(string Name)
    {
        this.Name = Name;
    }
    //Deserialize
    protected Visitor(SerializationInfo info, StreamingContext context)
    {
        this.Version = info.GetInt32("Version");
        this.Name = info.GetString("Name");
    }
    //Serialize
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Version", this.Version);
        info.AddValue("Name", this.Name);
    }
    [OnDeserialized]
    private void OnDeserialization(StreamingContext context)
    {
        switch (this.Version)
        {
            case 1:
                //Handle versioning issues, if this
                //deserialized version is one, so that
                //it can play well once it's serialized as
                //version two.
                break;
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新