JSON.Net:强制序列化所有私有字段和子类中的所有字段

JSON.Net: Force serialization of all private fields and all fields in sub-classes(JSON.Net:强制序列化所有私有字段和子类中的所有字段)

本文介绍了JSON.Net:强制序列化所有私有字段和子类中的所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几个不同类的类,我将这些类中的信息发送给客户,但我不想将它们全部发送出去,所以有些是私有的,有些有 [JsonObject(MemberSerialization.OptIn)] 标志等

I have a class with several different classes and I send the information in these classes out to clients but I don't want to send them all out so some are private, some have the [JsonObject(MemberSerialization.OptIn)] flag etc.

但是,现在我想在需要关闭服务器时以及每 12 小时(我不想使用数据库)备份所有这些对象,所以我想做的(如果可能的话)是强制 JSON.Net Serializer 转换对象和属于该对象的所有对象.

However, now I want to do a backup of all these objects when I need to shutdown the server and every 12 hours (I don't want to use a database) so what I want to do (if possible) is to force the JSON.Net Serializer to convert the object and all the object belonging to that object.

例如:

class Foo
{
  public int Number;
  private string name;
  private PrivateObject po = new PrivateObject();

  public string ToJSON()
  { /* Serialize my public field, my property and the object PrivateObject */ }
}

我尝试了这段代码(即使它已经过时),但它没有序列化与我的对象相关的对象:

I tried this code (even though it's obsolete) but it doesn't Serialize the objects related to my object:

Newtonsoft.Json.JsonSerializerSettings jss = new Newtonsoft.Json.JsonSerializerSettings();

Newtonsoft.Json.Serialization.DefaultContractResolver dcr = new Newtonsoft.Json.Serialization.DefaultContractResolver();
dcr.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic;
jss.ContractResolver = dcr;

return Newtonsoft.Json.JsonConvert.SerializeObject(this, jss);

推荐答案

这应该可行:

var settings = new JsonSerializerSettings() { ContractResolver = new MyContractResolver() };
var json = JsonConvert.SerializeObject(obj, settings);

<小时>

public class MyContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                        .Select(p => base.CreateProperty(p, memberSerialization))
                    .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                               .Select(f => base.CreateProperty(f, memberSerialization)))
                    .ToList();
        props.ForEach(p => { p.Writable = true; p.Readable = true; });
        return props;
    }
}

这篇关于JSON.Net:强制序列化所有私有字段和子类中的所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:JSON.Net:强制序列化所有私有字段和子类中的所有字段

基础教程推荐