0

Say i have a C# Class called Vehicle:

public class Vehicle {
    public int VehicleNumber {get;set;}
    public string SerialNumber {get;set;}
    public string Model {get;set;}
}

Now this is a function in a webApi controller:

public string Get(){
    return new Vehicle {VehicleNumber = 1, Model = "Lexus car"}
}

The Json object I would receive upon sending the get request would be:

{ "VehicleNumber" : 1, "SerialNumber" : null, "Model" = "Lexus Car"}

Is there a way to omit properties that are null from the end result? so that my final result would like so:

{ "VehicleNumber" : 1, "Model" = "Lexus Car"}

Edit: This question seemse to be very similar to another question that i have not encountered untill commented on this question.

But it is not entirely identical. Is there any way that with Data Annotations i can prevent serialization of a property if the property is null?

Bodokh
  • 976
  • 4
  • 15
  • 34

1 Answers1

0

After more research i have found that this question is a duplicate of this one here:

How to ignore a property in class if null, using json.net

This question provides the answer that i need.

Community
  • 1
  • 1
Bodokh
  • 976
  • 4
  • 15
  • 34