WebApi does not serialize null fields

I have the following command in my web api:

return Request.CreateResponse(HttpStatusCode.OK, MyDBContext.DB.Database.SqlQuery<MyCustomerClass>("SELECT * FROM CUSTOMER").ToList()); 

Here is the table:

 CREATE TABLE [dbo].[Customer] ( [CustomerID] [int] NOT NULL, [FirstName] [nvarchar](50) NOT NULL, [LastName] [nvarchar](50) NULL, CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED ([CustomerID] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO 

I found that when requesting data from webApi, if the fields are null , then the returned JSON result does not include this field in the return result. Is this expected behavior?

+1
source share
2 answers

I found that the fix was this: in the json formatter serializer settings:

 jsonFormatter.SerializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include }; 
+3
source

I do not think the expected behavior. At least in terms of JSON. I cannot talk much about WebAPI since I have not used it. In my project that uses JSON, if I were to issue the following code:

 # Package our response into an array... $response = array("type"=>"remove_from_distribution_list","results"); # And send it back to XMLHttpRequest object encoded... echo json_encode($response); 

with results that do not matter, the results will still be transmitted together. There will be no value next to him.

+1
source

Source: https://habr.com/ru/post/923095/


All Articles