我有一个包含几个不同类的类,我将这些类中的信息发送给客户端,但我不想将它们全部发送出去,因此有些是私有的,有些带有[JsonObject(MemberSerialization.OptIn)]标志等。
[JsonObject(MemberSerialization.OptIn)]
但是,现在我想在需要关闭服务器时每12小时备份一次所有这些对象(我不想使用数据库),所以我想做的(如果可能的话)是强制使用JSON .Net Serializer可以转换对象和属于该对象的所有对象。
例如:
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 */ } }
我尝试了这段代码(即使它已经过时了),但是它没有序列化与我的对象相关的对象:
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; } }