用
[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文档:
当您的应用程序从外部源反序列化JSON时,应谨慎使用TypeNameHandling。反序列化除None以外的其他值时,应使用自定义SerializationBinder验证传入的类型。



