The. Net core handles webapi JSON and returns annoying null and empty

Time:2021-9-7

preface

In project development, annoying nulls will be encountered in both the foreground and background. If the fields in the database table allow null values, the corresponding field type in the code entity class is nullable < >, such as int?, DateTime?, The values returned from the serialization of null value fields are null. The assignment of corresponding fields in the foreground requires null value judgment. How can null be replaced with null globally.

This article shares the method that web API interface services uniformly return null and replace it with null.

1、 Analyze problems

Newtonsoft.json is used for serialization in the. Net core, and the return format of the webapi interface is set globally through the startup.cs class. Would you like to know if NULL can be replaced with null by configuration? So we found out how newtonsoft.json handles the attributes of null and default values during serialization and deserialization. The specific configuration code is as follows:

1 public void ConfigureServices(IServiceCollection services)
 2 {
 3 // configure MVC + JSON serialization
 4     services.AddMvc()
 5         .AddNewtonsoftJson(options =>
 6         {
 7 // the data format is lowercase, without using hump small hump firstname large hump firstname
 8             options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
 9 // by default, the case of the metadata key is not changed
10             //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
11 // ignore circular reference
12             options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
13 // set time format
14             options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
15 // ignore null serialization of null values without attributes
16             //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
17 // the default value and null are ignored. 1. The default value and null of the property are not included
18             //options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Igno
19         })
20 }

 1. Processing of null values

When serializing and deserializing, you need to ignore the property with null value and set the value of serializersettings.nullvaluehandling

  • Nullvaluehandling.ignore ignores null values when serializing and deserializing objects.
  • Nullvaluehandling.include contains null values when serializing and deserializing objects.

2. Processing of default values

When serializing and deserializing, you need to ignore the default value attribute and set the value of serializersettings.defaultvaluehandling

  • Defaultvaluehandling.ignore ignores default values when serializing and deserializing
  • Defaultvaluehandling.include include default values when serializing and deserializing

3. Sample code

1 / * contains the default value of the property and null serialization*/
 2 {
 3   "Name": null,
 4   "Age": 0,
 5   "Partner": null,
 6   "Salary": 0.0
 7 }
 8 / * serialization of default values without attributes*/
 9 {
10   "Name": "Hello World",
11   "Age": 28
12 }
13 / * null serialization without attributes*/
14 {
15   "Name": "Hello World",
16   "Age": 28,
17   "Salary": 0.0
18 }

Through the above analysis: one is the default value serialization without attributes, and the other is the null serialization without attributes, which can not meet the current requirements. The null serialization returned by the interface is null.

2、 Problem solving

1. The default returned JSON result format of the project webapi is as follows:

1 {
 2   "code": 0,
 3 "MSG": "query succeeded",
 4   "data": {
 5     "id": 1,
 6 "title": "warm your stomach in hot summer",
 7     "describe": "",
 8     "author": null,
 9     "authorId": null,
10     "linkSource": null,
11     "author_Picture": null,
12 "content": "in hot summer, many people like to eat cold food to relieve the heat, but this practice is very harmful to their health.",
13   }
14 }

2. To solve the problem, replace all nulls with blanks, as shown in the following figure:

      The. Net core handles webapi JSON and returns annoying null and empty  The. Net core handles webapi JSON and returns annoying null and empty

3. Solution

You need to write a nulltoemptystringresolver class yourself, and then override camelcasepropertynamescontractresolver. However, this method can only solve the problem of string type null → “”, which is invalid for other nullable types, such as: int DateTime? Wait.

1 public class NullToEmptyStringResolver : CamelCasePropertyNamesContractResolver
 2 {
 3     /// 
 4 // create attribute
 5     /// 
 6 // type
 7 // serialize members
 8     /// 
 9     protected override IList CreateProperties(Type type, MemberSerialization memberSerialization)
10     {
11         return type.GetProperties().Select(c =>
12                 {
13                     var jsonProperty = base.CreateProperty(c, memberSerialization);
14                     jsonProperty.ValueProvider = new NullToEmptyStringValueProvider(c);
15                     return jsonProperty;
16                 }).ToList();
17     }
18 }
19 
20 public class NullToEmptyStringValueProvider : IValueProvider
21 {
22     private readonly PropertyInfo _memberInfo;
23     /// 
24 // constructor
25     /// 
26     /// 
27     public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
28     {
29         _memberInfo = memberInfo;
30     }
31 
32     /// 
33 // get value
34     /// 
35     /// 
36     /// 
37     public object GetValue(object target)
38     {
39         var result = _memberInfo.GetValue(target);
40         if (_memberInfo.PropertyType == typeof(string) && result == null)
41             result = string.Empty;
42         return result;
43     }
44 
45     /// 
46 // set value
47     /// 
48     /// 
49     /// 
50     public void SetValue(object target, object value)
51     {
52         _memberInfo.SetValue(target, value);
53     }
54 }

Modify the code marked in red in the startup.cs code, as shown below:

1 // configure MVC + JSON serialization
 2 services
 3     .AddMvc(options =>{options.EnableEndpointRouting = false;})
 4     .AddNewtonsoftJson(options =>
 5     {
 6 // by default, the case of the metadata key is not changed
 7         //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
 8 // the data format is lowercase, without using hump small hump firstname large hump firstname
 9         //options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
10         options.SerializerSettings.ContractResolver = new NullToEmptyStringResolver();
11 // ignore circular reference
12         options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
13 // set time format
14         options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
15 // ignore null serialization of null values without attributes
16         //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
17 // the default value and null are ignored. 1. The default value and null of the property are not included 
18         //options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Igno
19     })

After modifying the configuration, rerun is completed to achieve the effect of replacing null with empty. The operation results are as follows:

1 {
 2   "code": 0,
 3 "MSG": "query succeeded!",
 4   "data": {
 5     "id": 1,
 6 "title": "warm your stomach in hot summer",
 7     "describe": "",
 8     "author": "",
 9     "authorId": "",
10     "linkSource": "",
11     "author_Picture": "",
12     "source": 0,
13 "content": "in hot summer, many people like to eat cold food to relieve the heat, but this practice is very harmful to their health."
14   }
15 }

3、 Summary

During the serialization of newtonsoft.json in. Net core, the string null is replaced with empty. Through the contractresolver class, some serialization settings, custom attribute names, time formats, selective serialization attributes, etc. are added to the attribute to realize the unification of the JSON format returned by the web API.

 

Excellence is a habit. You are welcome to pay attention to your study