如何在使用 List<T> 进行序列化期间将空 JSON 属性默认为空数组JSON.NET 中的属性? [英] How to default a null JSON property to an empty array during serialization with a List&lt;T&gt; property in JSON.NET?

查看:50
本文介绍了如何在使用 List<T> 进行序列化期间将空 JSON 属性默认为空数组JSON.NET 中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有 JSON,它要么通过 HTTP 调用传入,要么存储在数据库中,但在服务器处理期间,它们被映射到 C# 对象.

Currently I have JSON that either comes in via an HTTP call or is stored in a database but during server processing they are mapped to C# objects.

这些对象具有像public List这样的属性.MyArray.

当 JSON 包含 MyArray:null 我希望结果属性为空 List 而不是 null List代码> 属性.

When the JSON contains MyArray:null I want the resulting property to be an empty List<T> instead of a null List<T> property.

目标是对象将重新序列化"为 JSON 为 MyArray:[],从而保存到数据库或通过 HTTP 作为空数组而不是 null.

The goal is that the object will "reserialize" to JSON as MyArray:[], thus either saving to the database or responding out via HTTP as an empty array instead of null.

那样,无论如何,C# 类基本上都会为任何 List<T> 属性清除并强制执行一个空数组,否则这些属性将是 null 并导致事情发生中断浏览器端代码(例如:cannot read property 'length' of null).

That way, no matter what, the C# class is basically scrubbing and enforcing an empty array for any List<T> property that would otherwise be null and cause things to break in the browser side code (for example: cannot read property 'length' of null).

有没有办法在序列化/反序列化期间,我可以让任何与 List 属性配对的空值变成空数组?

Is there a way that during the serialization/deserialization I can have any null value that is paired to a List<T> property become an empty array instead?

推荐答案

如果空列表为 null,你总是可以延迟加载它.

You could always lazy load an empty list if its null.

在 JsonDeserializer 上使用 NullValueHandling 选项.

Use the NullValueHandling option on the JsonDeserializer.

var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;

return JsonConvert.DeserializeObject<T>(json, settings);

http://james.newtonking.com/json/help/index.html?topic=html/SerializationSettings.htm

这篇关于如何在使用 List<T> 进行序列化期间将空 JSON 属性默认为空数组JSON.NET 中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆