skip to Main Content

I want to pass a null value to a key using post request in an api.

For example I want to pass the below json data. i.e Exp and TeamID is null

{
   "ID":162617,
   "TextKey":"107737",
   "Exp":null,
   "TeamID":null
}

the result is accepted in postman, but when I tried passing the same using c# code below. my json becomes invalid

long idvalue = 162617;
string textkeyvalue = "107737";
string expvalue = null;
long? teamIDvalue = null;

string postData = "{"ID":" + idvalue + ","TextKey":"" + textkeyvalue + "","Exp":"" + expvalue + "","TeamID":"" + teamIDvalue + ""}";

which gives me the following output.

{
   "ID":162617,
   "TextKey":"107737",
   "Exp":"",
   "TeamID":
}

and my request fails due to invalid json body. so how do i pass this sort of null data or null keyword?

Note :- All the Key value pairs are mandatory in my api so i cannot omit them if they are null.

I just want to pass the data in below format.

{
   "ID":162617,
   "TextKey":"107737",
   "Exp":null,
   "TeamID":null
}

2

Answers


  1. To answer your question, to write a text for null value you can do this :

    var result = "my value is " + (strValue ?? "null");
    

    or to add quotes

    var result = "my value is " + (strValue == null ? "null" : $""{strValue}"");
    

    you can also create a static helper method to make it easier

    static string write(string str) => str == null ? "null" : $""{str}"";
    static string write(long? value) => value == null ? "null" : value.ToString();
    

    so in your example it becomes :

    string postData = "{"ID":" + idvalue + ","TextKey":" + write(textkeyvalue) + ","Exp":" + write(expvalue) + ","TeamID":" + write(teamIDvalue) + "}";
    

    Better solution!

    create a class for the data model, and use a library (eg System.Text.Json) to serialize it, like so:

    public class MyData
    {
       public long ID { get; set; }
       public string TextKey { get; set; }
       public string Exp { get; set; }
       public long? TeamID { get; set; }
    }
    
    //construct model
    var data = new MyData()
    {
       ID = 162617,
       TextKey = "107737",
       Exp = null,
       TeamID = null,
    }
    
    //serialize to json
    var result = System.Text.Json.JsonSerializer.Serialize(data);
    
    Login or Signup to reply.
  2. @gepa’s answer is right on the money, but you can serialize an anonymous object, too:

    long idvalue = 162617;
    string textkeyvalue = "107737";
    string? expvalue = null;
    long? teamIDvalue = null;
    
    string postData = System.Text.Json.JsonSerializer.Serialize(new 
    {
        ID = idvalue,
        TextKey = textkeyvalue,
        Exp = expvalue,
        TeamID = teamIDvalue,
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search