What is the best way to notify api clients of null-valued properties of returned JSON object?

69 Views Asked by At

I have an asp.net web api 2 application that provides data in JSON format for api clients. For GET api methods, an api client programmer who is using Java and C++ languages to call those GET method apis. However, for null-valued properties of JSON objects, the client programmer says he receives "null" (null in-quote string) for those properties. In SQL Server database for nvarchar (string) and datetime columns of different database tables, I save those null-valued columns as null as normal SQL server convention but not "null" string.

My question is what is the best way to let api client programmers know if a null-valued property is null to distinguish it from real "null" string, e.g. {"state": "null"} a literal string. Thanks in advance.

I have many GET method apis which returns null for null-valued properties of JSON objects.

I test my GET Api methods for null properties with Postman or Advanced Rest Client tool, I do not see those tool returns null in "null" (in-quote string) for null-valued properties: (here is state and closeddate properties)

{"firstname":"abc","lastname":"def","state":null,"birthdate":"1992-05-25T00:00:00","closeddate":null}

One of GET method api looks like:

[HttpGet]
public HttpResponseMessage GetUserInfo(int userid)
{
        var user = _userService.GetUserInfo(userid);
        var statusCode = _userService.StatusCode;
        var errorCode = _userService.ErrorCode;

        return _statusCode == HttpStatusCode.OK
          ? Request.CreateResponse(_statusCode, account)
          : Request.CreateResponse(_statusCode, errorCode);
}
1

There are 1 best solutions below

0
On

Since you are asking for an opinion, here's one from the creator of SlashDB API: when in doubt, leave it out.

In the JSON data format keys with null value can be omitted from the result.

The following API call returns a Customer record, which does not have a value in the Company field:

XML format is more formal about it because you can define a schema, which prescribes what is the allowed shape of data. In particular, an element (tag) could have a minOccurs=0 attribute to indicate its optionality, and/or a nillable=True to indicate that a tag could be present without a value (i.e. ). For completeness here's the same record in XML and its schema: