【问题标题】:How to automatically include type information when serializing?序列化时如何自动包含类型信息?
【发布时间】:2021-11-01 17:12:27
【问题描述】:

在序列化类中的属性时,是否可以指定我总是需要 json 对象中的类型信息? (最好使用 Newtonsoft)。 我在想这样的事情:

public abstract class Value {...}
public class BigValue : Value {...}
public class SmallValue : Value {...}

public class ValueContainer
{
    [JsonSetting(TypenameHandling = TypenameHandling.All)] // <--- Something like this?
    public Value TheValue { get; set; }
}

我知道我可以在使用自定义转换器进行解析时指定此行为。 但是我希望每次序列化这种类型的对象时都包含类型信息,而不必手动指定要使用的序列化选项。

【问题讨论】:

  • 是的,使用custom converter
  • 是的,这是一个解决方案,但是每次我必须序列化 ValueContainer 对象时,我都必须再次手动指定要使用此转换器。有没有办法指定它,然后不必再次处理?
  • @SørenHN 与指定 TypeNameHandling 相同 - 使用 JsonPropertyAttribute
  • 这很大程度上取决于您如何使用 Json.Net。您通常可以在 web api 之类的东西中指定默认转换器。但你实际上并没有具体说明你如何使用 Json.Net,所以我无法回答这个问题

标签: c# json.net


【解决方案1】:

Newtonsoft.JsonJsonPropertyAttribute 具有您可以设置的TypeNameHandling 属性:

public class Root
{
    [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
    public Base Prop { get; set; }
}
public class Base
{
    public int IntProp { get; set; }
}
public class Child:Base
{
}

// Example:
var result = JsonConvert.SerializeObject(new Root
{
    Prop = new Child()
});
Console.WriteLine(result);  // prints {"Prop":{"$type":"SOAnswers.TestTypeNamehandling+Child, SOAnswers","IntProp":0}}

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    相关资源
    最近更新 更多