0

我正在使用 Json.NET(也尝试过 DataContractJsonSerializer),但我只是不知道在序列化/反序列化时如何处理没有命名的数组?

我的 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"
            },
           ...
          ],
          ...
      ]
...
}
4

1 回答 1

0

I think the only solution is a custom JsonConverter. Your code should look like this:

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);
    }
}

Then you have to decorate your Subheading class with a JsonConverterAttribute:

[JsonConverter(typeof(SubheadingJsonConverter)]
public class Subheading
{
    // ...
}
于 2012-08-14T13:02:11.967 回答