具有内部属性的JSON序列化器对象 [英] JSON Serializer object with internal properties
问题描述
我的类具有一些内部属性,我也想将它们序列化为json.我怎样才能做到这一点? 例如
I have class with some internal properties and I would like to serialize them into json as well. How can I accomplish this? For example
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"
}
推荐答案
使用然后再进行测试:
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"是我正在使用的名称空间和程序集名称).
(Where "Tile.JsonInternalPropertySerialization" and "Tile" are namespace and assembly names I am using).
顺便说一句,在使用TypeNameHandling
时,请务必从
As an aside, when using TypeNameHandling
, do take note of this caution from the Newtonsoft docs:
当您的应用程序从外部源反序列化JSON时,应谨慎使用TypeNameHandling.反序列化除None以外的其他值时,应使用自定义SerializationBinder验证传入的类型.
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.
有关为什么可能需要这样做的讨论,请参见 Newtonsoft Json中的TypeNameHandling警告 和 由于Json.Net TypeNameHandling自动而易受外部json影响吗? .
For a discussion of why this may be necessary, see TypeNameHandling caution in Newtonsoft Json and and External json vulnerable because of Json.Net TypeNameHandling auto?.
这篇关于具有内部属性的JSON序列化器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!