具有内部属性的JSON序列化程序对象

本文关键字:序列化 程序 对象 JSON 内部 属性 | 更新日期: 2023-09-27 18:30:06

我有一个带有一些内部属性的类,我也想将它们序列化为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"
}

具有内部属性的JSON序列化程序对象

[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"answers"Tile"是我正在使用的命名空间和程序集名称)。

顺便说一句,当使用TypeNameHandling时,请注意Newtonsoft文档中的这一警告:

当应用程序从外部源反序列化JSON时,应谨慎使用TypeNameHandling。当使用None以外的值进行反序列化时,应使用自定义SerializationBinder验证传入类型。

有关为什么需要这样做的讨论,请参阅Newtonsoft Json中的TypeNameHandling警告由于Json.Net TypeNameHanding auto而导致外部Json易受攻击