gpt4 book ai didi

c# - 具有内部属性的 JSON Serializer 对象

转载 作者:行者123 更新时间:2023-11-30 18:11:37 27 4
gpt4 key购买 nike

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

Console.WriteLine(jsonOutput);

我得到以下输出:

{
"$type": "Tile.JsonInternalPropertySerialization.Foo, Tile",
"num1": 101,
"num2": 202.0,
"Description": "Foo Example"
}

(其中“Tile.JsonInternalPropertySerialization”和“Tile”是我正在使用的命名空间和程序集名称)。

顺便说一句,在使用TypeNameHandling 时,请注意 Newtonsoft docs 中的警告:

TypeNameHandling should be used with caution when your application deserializes JSON from an external source. Incoming types should be validated with a custom SerializationBinder when deserializing with a value other than None.

有关为什么这可能是必要的讨论,请参阅 TypeNameHandling caution in Newtonsoft Json External json vulnerable because of Json.Net TypeNameHandling auto? .

关于c# - 具有内部属性的 JSON Serializer 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497118/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com