JSON 序列化:类包含泛型类型的泛型集合

Fra*_*ith 5 c# generics json json.net

我正在尝试将 .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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,如下:

public class Fum
{
  public string FumName {get; set;}
  public list<IFoo> Foos {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我创建实例如下:

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");
Run Code Online (Sandbox Code Playgroud)

然后...

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

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

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

{
  "FumName": "myFum",
  "Foos" : [
    {
      "Name": "intFoo",
      "ValueType": "System.Int32"
    },
    {
      "Name": "boolFoo",
      "ValueType": "System.Boolean"
    },
    {
      "Name": "stringFoo",
      "ValueType": "System.String"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

Con*_*des 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!"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)