C# 具有内部属性的JSON序列化程序对象
我有一个带有一些内部属性的类,我也想将它们序列化为json。我怎样才能做到这一点? 比如说C# 具有内部属性的JSON序列化程序对象,c#,.net,json,C#,.net,Json,我有一个带有一些内部属性的类,我也想将它们序列化为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.I
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);
}
我明白了
使用属性标记要序列化的内部属性:
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”是我正在使用的命名空间和程序集名称)
在使用typenameholling
时,请注意以下注意事项:
当应用程序从外部源反序列化JSON时,应谨慎使用TypeNameHandling。当使用非None的值反序列化时,应使用自定义SerializationBinder验证传入类型
有关为什么需要这样做的讨论,请参见和。通常内部属性不会离开当前程序集的边界,因此不会被序列化。你为什么要这么做?如果你想要一个合适的JSON表示,你可能需要一个DTO来映射你的内部/私有内容,然后序列化。+1@DarinDimitrov说的。但是如果您真的想这样做,我相信您需要子类
DefaultContractResolver
,使它也可以查看非公共属性。可能的重复只是用属性标记它们。如果类也是内部的,则用[JsonObject()]标记它
我刚刚删除了我的回答,说内部属性在程序集之外是不可访问的,因为这对我来说是新闻。序列化程序如何能够跨程序集访问这些文件?这不是什么安全问题吗?@esmoore68-序列化程序使用反射。参见例如和。
{
"$type": "Tile.JsonInternalPropertySerialization.Foo, Tile",
"num1": 101,
"num2": 202.0,
"Description": "Foo Example"
}