具有内部属性的JSON Serializer对象
我有一些内部属性的类,我想将它们序列化为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()]
属性标记内部属性:
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); Debug.WriteLine(jsonOutput);
我得到以下输出:
{ "$type": "Tile.JsonInternalPropertySerialization.Foo, Tile", "num1": 101, "num2": 202.0, "Description": "Foo Example" }
(其中“Tile.JsonInternalPropertySerialization”和“Tile”是我正在使用的命名空间和程序集名称)。