.NET 的哪种 JSON 序列化程序会将项目插入列表而不是替换列表?
好的,我有这个基本的类设置...
public class Location
{
public string Name{ get; set; }
private LocationList _LocationList = new LocationList();
public LocationList Locations{ get{ return _LocationList; } }
}
public class LocationList : List<Location>{}
public class ViewModel
{
private LocationList _LocationList = new LocationList();
public LocationList Locations{ get{ return _LocationList; } }
}
我想将其与 Newtonsoft JSON 序列化器一起使用。但是,序列化程序不会将项目插入只读属性访问器后面的现有集合中,而是尝试将一个全新的 List 分配给该属性,这当然不能,因为没有设置器。
现在我可以切换到这个...
public class Location
{
public string Name{ get; set; }
public LocationList Locations{ get; set; }
}
public class LocationList : List<Location>{}
public class ViewModel
{
public LocationList RootLocations{ get; set; }
}
但是现在列表属性不是只读的并且可以设置为空。即使我们将setter设为私有,JSON反序列化仍然可以将其设置为null。
我想要的是一种告诉序列化器“将列表中的项目插入到这个已经存在的列表中”的方法,而不是说“用你的列表完全替换我的列表”。
那么这可以完成吗,还是我必须编写自己的 JSON 序列化转换器并将其插入?
中号
Ok, so I have this basic class setup...
public class Location
{
public string Name{ get; set; }
private LocationList _LocationList = new LocationList();
public LocationList Locations{ get{ return _LocationList; } }
}
public class LocationList : List<Location>{}
public class ViewModel
{
private LocationList _LocationList = new LocationList();
public LocationList Locations{ get{ return _LocationList; } }
}
which I want to use with the Newtonsoft JSON serializer. However, the serializer doesn't insert the items into the existing collection behind the read-only property accessor, but rather tries to assign an entirely new List to the property, which of course it can't since there isn't a setter.
Now I could just switch to this...
public class Location
{
public string Name{ get; set; }
public LocationList Locations{ get; set; }
}
public class LocationList : List<Location>{}
public class ViewModel
{
public LocationList RootLocations{ get; set; }
}
But now the list property isn't read-only and can be set to null. Even if we make the setter private, JSON deserialization can still set it to null.
What I want is a way to tell the serializer 'Take the items you have in your list and insert them into this already-existing list' rather than saying 'Replace my list with yours altogether'.
So can this be done, or am I going to have to write my own JSON serialization converter and plug that in?
M
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不了解 JSON.NET,但如果您使用 JavaScriptSerializer,您可以提供自定义序列化程序,但仍使用内置的解析/格式化等:
I don't know about JSON.NET, but if you use
JavaScriptSerializer
you can provide a custom serializer, but still use the inbuilt parsing / formatting etc: