2012-11-30 89 views
4

我想将一个.NET类序列化为JSON,其中包含属性,该属性是泛型类型的泛型列表。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字符串,名称和值类型属性 - 然而,值始终从输出省略:

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

任何人都可以提出一种方法,这将允许我正确地序列化 泛型类型实例的列表,使Value属性包含在内?

回答

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!" 
     } 
    ] 
    } 
} 
相关问题