我有一个JsonConverter
,它取决于特定标志,需要
- 运行自定义序列化逻辑
- 运行默认JSON.NET序列化逻辑
如何从 JsonConverter
?
谢谢
这是一个示例。说出您的班级以这样的序列化:
class Foo
{
public bool IsSpecial { get; set; }
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
IsSpecial
标志用于控制我们在转换器中做的事情还是让事情自然序列化。您可以像这样编写转换器:
class FooConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Foo).IsAssignableFrom(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Foo foo = (Foo)value;
JObject jo;
if (foo.IsSpecial)
{
// special serialization logic based on instance-specific flag
jo = new JObject();
jo.Add("names", string.Join(", ", new string[] { foo.A, foo.B, foo.C }));
}
else
{
// normal serialization
jo = JObject.FromObject(foo);
}
jo.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
然后,要使用转换器,请将其实例传递到SerializeObject
方法(例如在设置中)。(请勿使用JsonConverter
属性装饰目标类,否则将在序列化时导致无限的递归环。)
class Program
{
static void Main(string[] args)
{
List<Foo> foos = new List<Foo>
{
new Foo
{
A = "Moe",
B = "Larry",
C = "Curly",
IsSpecial = false
},
new Foo
{
A = "Huey",
B = "Dewey",
C = "Louie",
IsSpecial = true
},
};
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new FooConverter());
settings.Formatting = Formatting.Indented;
string json = JsonConvert.SerializeObject(foos, settings);
Console.WriteLine(json);
}
}
输出:
[
{
"IsSpecial": false,
"A": "Moe",
"B": "Larry",
"C": "Curly"
},
{
"names": "Huey, Dewey, Louie"
}
]
您可以更改CANWRITE属性以禁用自定义序列化器。如果物体可以包含相同类型的孩子或您在多个线程中序列化,则这将无法正常工作。
class FooConverter : JsonConverter
{
bool _canWrite = true;
public override bool CanWrite
{
get { return _canWrite;}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Foo foo = (Foo)value;
JObject jo;
if (foo.IsSpecial)
{
// special serialization logic based on instance-specific flag
jo = new JObject();
jo.Add("names", string.Join(", ", new string[] { foo.A, foo.B, foo.C }));
}
else
{
// normal serialization
_canWrite = false;
jo = JObject.FromObject(foo);
_canWrite = true;
}
jo.WriteTo(writer);
}
}