好的,我们正在使用我非常喜欢的 Newtonsoft 的 JSON.NET 产品。但是,我有一个简单的类结构,用于分层位置,大致如下所示......
public class Location
{
public string Name{ get; set; }
public LocationList Locations{ get; set; }
}
// Note: LocationList is simply a subclass of a List<T>
// which then adds an IsExpanded property for use by the UI.
public class LocationList : List<Location>
{
public bool IsExpanded{ get; set; }
}
public class RootViewModel
{
public LocationList RootLocations{ get; set; }
}
...当我将它们序列化为 JSON 时,一切都很好,除了 LocationList 类上的 IsExpanded 属性被排除在外。只有列表的内容被序列化。
现在这就是我所设想的一种很好的格式。它本质上就像LocationList
不是一个子类,List<Location>
而是一个普通对象,它有一个名为Items
type的属性List<Location>
。
{
"Locations":
{
"IsExpanded": true,
"Items": [
{
"Name": "Main Residence",
"Locations":
{
"IsExpanded": true,
"Items": [
{
"Name": "First Floor",
"Locations":
{
"IsExpanded": false,
"Items": [
{
"Name": "Livingroom"
},
{
"Name": "Dining Room"
},
{
"Name": "Kitchen"
}
]
},
{
"Name": "Second Floor",
"Locations":
{
"IsExpanded": false,
"Items": [
{
"Name": "Master Bedroom"
},
{
"Name": "Guest Bedroom"
}
]
},
{
"Name": "Basement"
}
]
}
}
]
}
}
现在我也了解到 Newtonsoft 的产品是可扩展的,因为他们专门讨论了如何为特定数据类型编写自己的自定义序列化程序,这正是我在这里想要的。但是,他们没有关于如何执行此操作的任何好的代码示例。
如果我们(SO 社区)能够解决这个问题,从技术上讲,通过使用上述格式,我们应该能够序列化 List 的任何子类(或其衍生物/类似对象),只要它们还没有一个名为的属性Items
(恕我直言)首先是一个糟糕的设计,因为它会像垃圾一样令人困惑!)也许我们甚至可以让 Newtonsoft 在他们的序列化器中原生地推出这样的东西!
这么说……有人知道如何自定义序列化器/反序列化器以区别对待这个对象吗?
米