gpt4 book ai didi

c# - 从 JsonConverter 运行默认序列化逻辑

转载 作者:IT王子 更新时间:2023-10-29 04:05:13 24 4
gpt4 key购买 nike

我有一个 JsonConverter,根据实例特定的标志,它需要要么

  • 运行自定义序列化逻辑
  • 运行默认的 Json.NET 序列化逻辑

如何从 JsonConverter 运行默认的 Json.NET 序列化逻辑?

谢谢

最佳答案

这是一个例子。假设您要序列化的类看起来像这样:

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"
}
]

关于c# - 从 JsonConverter 运行默认序列化逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21366328/

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