我有一些内部属性的类,我也想将它们序列化为json。我该怎么做?例如
public class Foo { internal int num1 { get; set; } internal double num2 { get; set; } public string Description { get; set; } public override string ToString() { if (!string.IsNullOrEmpty(Description)) return Description; return base.ToString(); } }
使用保存
Foo f = new Foo(); f.Description = "Foo Example"; JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; string jsonOutput = JsonConvert.SerializeObject(f, Formatting.Indented, settings); using (StreamWriter sw = new StreamWriter("json_file.json")) { sw.WriteLine(jsonOutput); }
我懂了
{ "$type": "SideSlopeTest.Foo, SideSlopeTest", "Description": "Foo Example" }
用[JsonProperty]属性标记要序列化的内部属性:
[JsonProperty]
public class Foo { [JsonProperty] internal int num1 { get; set; } [JsonProperty] internal double num2 { get; set; } public string Description { get; set; } public override string ToString() { if (!string.IsNullOrEmpty(Description)) return Description; return base.ToString(); } }
然后再测试:
Foo f = new Foo(); f.Description = "Foo Example"; f.num1 = 101; f.num2 = 202; JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; var jsonOutput = JsonConvert.SerializeObject(f, Formatting.Indented, settings); Console.WriteLine(jsonOutput);
我得到以下输出:
{ "$type": "Tile.JsonInternalPropertySerialization.Foo, Tile", "num1": 101, "num2": 202.0, "Description": "Foo Example" }
(其中“ Tile.JsonInternalPropertySerialization”和“ Tile”是我正在使用的名称空间和程序集名称)。
顺便说一句 ,使用时TypeNameHandling,千万注意从这个谨慎的Newtonsoft文档:
TypeNameHandling
当您的应用程序从外部源反序列化JSON时,应谨慎使用TypeNameHandling。反序列化除None以外的其他值时,应使用自定义SerializationBinder验证传入的类型。