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

时间:2012-11-30 18:19:34

标签: c# json generics 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();
    }
}

然后,如下:

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属性?

1 个答案:

答案 0 :(得分:0)

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