问题描述
如果我有这样的课程:
[DataContract(Name = "", Namespace = "")]
public class MyDataObject
{
[DataMember(Name = "NeverNull")]
public IList<int> MyInts { get; set; }
}
当以下字符串反序列化时,有没有办法使MyInts字段成为非空的空列表?
Is there a way I can make MyInts field a non-null empty list when the following string is deserialized?
string serialized = @"{""NeverNull"":null}";
MyDataObject myDataObject = JsonConvert.DeserializeObject<MyDataObject>(serialized);
我正在使用Newtonsoft.Json
I’m using Newtonsoft.Json
我问的原因是我要解析一个相当复杂的json请求,它包含对象列表的嵌套,并且我想通过反序列化代码来创建这些对象,以便避免很多空检查:
The reason I ask is that I have a fairly complicated json request to parse, it contains nests of lists of objects and I'd like the deserialization code to create these object so I can avoid lots of null checks:
if (foo.bar != null)
{
foreach (var bar in foo.bar)
{
if (bar.baz != null)
{
foreach (var baz in bar.baz)
{
...
推荐答案
也许添加反序列化后的回调,以便在反序列化结束时对此进行检查?
Perhaps add a post-serialization callback that checks this at the end of deserialization?
[DataContract(Name = "", Namespace = "")]
public class MyDataObject
{
[OnDeserialized]
public void OnDeserialized(StreamingContext context)
{
if (MyInts == null) MyInts = new List<int>();
}
[DataMember(Name = "NeverNull")]
public IList<int> MyInts { get; set; }
}
还要注意,JsonConvert
(与DataContractSerializer
不同)执行默认的构造函数,因此通常您还可以添加一个默认的构造函数:
Note also that JsonConvert
(unlike DataContractSerializer
) executes the default constructor, so usually you could also have just added a default constructor:
public MyDataObject()
{
MyInts = new List<int>();
}
但是,在这种情况下,爆炸 "NeverNull":null
在反序列化期间将其更改回null
,因此为什么我在上面使用了回调.
however, in this case the explict "NeverNull":null
changes it back to null
during deserialization, hence why I've used a callback above instead.
这篇关于反序列化,以使字段为空列表而不是null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!