Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trouble turning class into API call body with null properties

The following code snippet I use to send a response to an endpoint:

 public static async Task PostPosition(string authorizationHeader, string apiUrl, string subDirectory, string xRoutingToken, string xApiKey, CustomObject payload)
 {
     using (HttpClient client = new HttpClient())
     {
         // Set up headers
         client.DefaultRequestHeaders.Add("Accept", "application/json, text/plain");
         client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
         client.DefaultRequestHeaders.Add("x-api-key", xApiKey);
         client.DefaultRequestHeaders.Add("x-routing-token", xRoutingToken);

         Console.WriteLine(apiUrl+subDirectory);

        
         string jsonPayload = System.Text.Json.JsonSerializer.Serialize(payload);
         var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

         try
         {
             HttpResponseMessage response2 = await client.PostAsync(apiUrl + subDirectory, content);
             Console.WriteLine($"Response Code: {response2.StatusCode}");
             Console.WriteLine($"Response Content: {await response2.Content.ReadAsStringAsync()}");
         }
         catch
         {
             Console.WriteLine("Position failed to send");
         }

         
     }
 }

The problem is sending a custom object with null values. My constructor for the custom object is here:

namespace Project
{
    // make two constructors; one for every field that I'll actually use

    public class CustomObject
    {

        public string id { get; set; }
        public string? unit_address { get; set; }
        public string? position_date { get; set; }
        public double? latitude { get; set; }
        public double? longitude { get; set; }
        public string? position_status { get; set; }
        public string? position_type { get; set; }
        public bool? ignition { get; set; }
        public int? speed { get; set; }
        public string? direction { get; set; }
        public long? odometer { get; set; }

        // first has every property
        public customObject(string objectId,
        string unitAddress,
        string positionDate,
        double lat,
        double lon,
        string posStatus,
        string posType,
        bool ign,
        int spd,
        string dir,
        long odom)
        {
            id = objectId;
            unit_address = unitAddress;
            position_date = positionDate;
            latitude = lat;
            longitude = lon;
            position_status = posStatus;
            position_type = posType;
            ignition = ign;
            speed = spd;
            direction = dir;
            odometer = odom;

        }
        // second has every field I'll use
        public customObect( string iid, double llatitude, double llongitude, string ppositionDate, )
        {
            this.id = iid;
            this.latitude = llatitude;
            this.longitude = llongitude;
            this.position_date = ppositionDate;

        }

    }
}

The endpoints I’m posting too don’t require all values hence me just sending date, lat, long, and id. When I use an anonymous object, I successfully make the call. Here is the anonymous object I use:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var payload2 = new
{
    id = "IDNUMBERHERE",
    position_date = "20230101010000-0400",
    latitude = 35.542887,
    longitude = -79.778473,
};

When I create a new CustomObject, null values get inserted into the other properties of the object. For example, when I use the following constructor:

CustomObject payload3 = new CustomObject("IDHere", 35.542887, -79.778473, "20230101010000-0400");

After serializing, the CustomObject looks like this:

{
  "id": "IDHere",
  "unit_address": null,
  "position_date": "20230101010000-0400",
  "latitude": 35.542887,
  "longitude": -79.778473,
  "position_status": null,
  "position_type": null,
  "ignition": null,
  "speed": null,
  "direction": null,
  "odometer": null
}

I need it to look like this:

{
  "id": "IDHere",
  "position_date": "20230101010000-0400",
  "latitude": 35.542887,
  "longitude": -79.778473,
}

How can I change my constructor, class, or serializer to accomodate this? Thank you everyone! This has caused me two days of headache!

>Solution :

You can configure the serializer to ignore all null-value properties. For example:

var payload = new CustomObject("IDHere", 35.542887, -79.778473, "20230101010000-0400");
var jsonPayload = JsonSerializer.Serialize(payload, new JsonSerializerOptions
{
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
});

The resulting value of jsonPayload is:

{
  "id": "IDHere",
  "position_date": "20230101010000-0400",
  "latitude": 35.542887,
  "longitude": -79.778473
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading