【问题标题】:JSON serialization: class contains a generic collection of generic typesJSON序列化:类包含泛型类型的泛型集合
【发布时间】:2012-11-30 18:19:33
【问题描述】:

我正在尝试将 .NET 类序列化为 JSON,其中包含一个属性,该属性是泛型类型的通用列表。

我的泛型类型定义如下:

public interface IFoo {}

public class Foo<T>: IFoo
{
  public string Name {get; set;}
  public string ValueType {get; set;}
  public T Value {get; set:}

    public Foo(string name, T value)
    {
      Name = name;
      Value = value;
      ValueType = typeof(T).ToString();
    }
}

那么,如下:

public class Fum
{
  public string FumName {get; set;}
  public list<IFoo> Foos {get; set;}
}

我创建实例如下:

myFum = new Fum();
myFum.FumName = "myFum";
myFum.Foos.Add(new Foo<int>("intFoo", 2);
myFum.Foos.Add(new Foo<bool>("boolFoo", true);
myFum.Foos.Add(new Foo<string>("stringFoo", "I'm a string");

那么……

我正在尝试使用 NewtonSoft JSON 库进行如下序列化:

string strJson = JsonConvert.SerializeObject(data, 
                  Formatting.Indented, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Include,
            TypeNameHandling = TypeNameHandling.All,
            TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
        });

在生成的 JSON 字符串中,每个 Foo 实例的 Name 和 ValueType 属性 已正确序列化 - 但是,输出中始终省略值:

{
  "FumName": "myFum",
  "Foos" : [
    {
      "Name": "intFoo",
      "ValueType": "System.Int32"
    },
    {
      "Name": "boolFoo",
      "ValueType": "System.Boolean"
    },
    {
      "Name": "stringFoo",
      "ValueType": "System.String"
    }
  ]
}

任何人都可以提出一种可以让我正确序列化的方法吗 泛型类型实例列表,以便包含 Value 属性?

【问题讨论】:

    标签: c# json generics json.net


    【解决方案1】:

    默认情况下,Json.NET 可能会忽略泛型类型,使用 [JsonProperty] 属性对其进行标记可以解决此问题。只是一个想法,它可能会或可能不会起作用。我现在无法测试它,但我会尝试并告诉你它是否真的有效。

    编辑:我认为这可能是您正在使用的 json.net 版本,因为我刚刚使用 NuGet 的版本测试了您的代码并收到以下输出:

    {
      "$type": "Testing.Fum, Testing",
      "FumName": "myFum",
      "Foos": {
        "$type": "System.Collections.Generic.List`1[[Testing.IFoo, Testing]], mscorlib",
        "$values": [
          {
            "$type": "Testing.Foo`1[[System.Int32, mscorlib]], Testing",
            "Name": "intFoo",
            "ValueType": "System.Int32",
            "Value": 2
          },
          {
            "$type": "Testing.Foo`1[[System.Boolean, mscorlib]], Testing",
            "Name": "boolFoo",
            "ValueType": "System.Boolean",
            "Value": true
          },
          {
            "$type": "Testing.Foo`1[[System.String, mscorlib]], Testing",
            "Name": "stringFoo",
            "ValueType": "System.String",
            "Value": "I'm a string!"
          }
        ]
      }
    }
    

    【讨论】:

    • 刚刚遇到了同样的问题,泛型类型没有被正确序列化,并且使用给定的序列化程序选项和最新版本它工作得很好。但是,请注意:这仍然不适用于 .NET 3.1/5.0 版本(System.Text.Json),因为它们还不支持序列化泛型(截至今天)。
    • 并记得在反序列化时使用相同的序列化程序选项,否则它也不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    相关资源
    最近更新 更多