skip to Main Content

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:

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!

2

Answers


  1. 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
    }
    
    Login or Signup to reply.
  2. This CustomObject class allows flexibility in creating instances with only the properties needed for a particular scenario.

    public class CustomObject
    {
        // Properties for 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; }
    
        // Constructor with optional parameters
        // Allows creating CustomObject with specified properties
        public CustomObject(
            string id,
            string? unit_address = null, // Optional parameter, default is null
            string? position_date = null, // Optional parameter, default is null
            double? latitude = null, // Optional parameter, default is null
            double? longitude = null, // Optional parameter, default is null
            string? position_status = null, // Optional parameter, default is null
            string? position_type = null, // Optional parameter, default is null
            bool? ignition = null, // Optional parameter, default is null
            int? speed = null, // Optional parameter, default is null
            string? direction = null, // Optional parameter, default is null
            long? odometer = null) // Optional parameter, default is null
        {
            // Assign values to properties
            this.id = id;
            this.unit_address = unit_address;
            this.position_date = position_date;
            this.latitude = latitude;
            this.longitude = longitude;
            this.position_status = position_status;
            this.position_type = position_type;
            this.ignition = ignition;
            this.speed = speed;
            this.direction = direction;
            this.odometer = odometer;
        }
    }
    
    // Creating an instance of CustomObject with specific properties
    CustomObject payload3 = new CustomObject(
        id: "IDHere",
        position_date: "20230101010000-0400",
        latitude: 35.542887,
        longitude: -79.778473
    );
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search