2012-08-14 102 views
0

我正在使用Json.NET(也试过DataContractJsonSerializer),但我无法弄清楚如何处理没有命名的数组时串行化/ deserialising?我如何使用Json.NET或其他序列化程序序列化/反序列化Json *没有命名*数组

我的C#类是这个样子:

public class Subheading 
{ 
    public IList<Column> columns { get; set; } 

    public Subheading() 
    { 
     Columns = new List<Column>(); 
    } 

} 

public class Column 
{ 
    public IList<Link> links { get; set; } 

    public Column() 
    { 
     Links = new List<Link>(); 
    } 

} 

public class Link 
{ 
    public string label { get; set; } 
    public string url { get; set; } 

} 

正在生成JSON是这样的:

{ 
      "columns": [ 
      { 
       "**links**": [ 
       { 
        "label": "New Releases", 
        "url": "/usa/collections/sun/newreleases" 
       }, 
       ... 
       ] 
      }, 
      ] 
    ... 
} 

我该怎么做,以松散的“链接”,使之像这样?:

{ 
     "columns": [ 
      [ 
      { 
       "label": "New Releases", 
       "url": "/usa/collections/sun/newreleases" 
      }, 
      ... 
      ], 
      ... 
     ] 
... 
} 

回答

0

我认为唯一的解决办法是自定义JsonConverter。您的代码应该是这样的:

class SubheadingJsonConverter : JsonConverter 
{ 
    public override bool CanConvert(Type objectType) 
    { 
     // tell Newtonsoft that this class can only convert Subheading objects 
     return objectType == typeof(Subheading); 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     // you expect an array in your JSON, so deserialize a list and 
     // create a Subheading using the deserialized result 
     var columns = serializer.Deserialize<List<Column>>(reader); 

     return new Subheading { column = columns }; 
    } 

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     // when serializing "value", just serialize its columns 
     serializer.Serialize(writer, ((Subheading) value).columns); 
    } 
} 

然后你有一个JsonConverterAttribute来装饰您的Subheading类:

[JsonConverter(typeof(SubheadingJsonConverter)] 
public class Subheading 
{ 
    // ... 
}