2012-08-14 97 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 
{ 
    // ... 
}