JSON.Net: Force serialization of all private fields and all fields in sub-classes(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:强制序列化所有私有字段和子类中的所有字段
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 使用 rss + c# 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01