我正在使用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"
},
...
],
...
]
...
}
答案 0 :(得分: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);
}
}
然后,您必须使用Subheading
JsonConverterAttribute
课程
[JsonConverter(typeof(SubheadingJsonConverter)]
public class Subheading
{
// ...
}