問(wèn)題描述
我有一個(gè)包含幾個(gè)不同類的類,我將這些類中的信息發(fā)送給客戶,但我不想將它們?nèi)堪l(fā)送出去,所以有些是私有的,有些有 [JsonObject(MemberSerialization.OptIn)]
標(biāo)志等
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.
但是,現(xiàn)在我想在需要關(guān)閉服務(wù)器時(shí)以及每 12 小時(shí)(我不想使用數(shù)據(jù)庫(kù))備份所有這些對(duì)象,所以我想做的(如果可能的話)是強(qiáng)制 JSON.Net Serializer 轉(zhuǎn)換對(duì)象和屬于該對(duì)象的所有對(duì)象.
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 */ }
}
我嘗試了這段代碼(即使它已經(jīng)過(guò)時(shí)),但它沒(méi)有序列化與我的對(duì)象相關(guān)的對(duì)象:
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);
推薦答案
這應(yīng)該可行:
var settings = new JsonSerializerSettings() { ContractResolver = new MyContractResolver() };
var json = JsonConvert.SerializeObject(obj, settings);
<小時(shí)>
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;
}
}
這篇關(guān)于JSON.Net:強(qiáng)制序列化所有私有字段和子類中的所有字段的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!