Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

c# - How to default a null JSON property to an empty array during serialization with a List<T> property in JSON.NET?

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.

These objects have properties like public List<int> MyArray.

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

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.

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).

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

OR

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...