Ad

Serialize Empty Object Instead Of Null In Newtonsoft.JSON

this is bothering me for some time. I've got model:

public class Main
{
    public Header header { get; set; }
    public Response response { get; set; }
}

public class Response
{
    public string projectId { get; set; }
    public string designBriefId { get; set; }
    public MDT mdt { get; set; }
    public List<ReferenceMDT> referenceMDT { get; set; }
    public List<ProductList> ProductList { get; set; }

}
public class MDT
{
    [Key]
    public string mdtAssetId { get; set; }
    public bool isMDTDownloaded { get; set; }
    public bool isNamingConventionCorrect { get; set; }
}

Whenever I'm Serializing this object to a JSON using:

Newtonsoft.Json

I'm then getting invalid (from API POV I'm working on) JSON conversion on empty/null object:

{
  "header": "unimportant",
  "response": {
    "projectId": "Prj_02022022_2",
    "designBriefId": "DB_02022022_4",
    "mdt": null,
    "referenceMDT": [],
    "ProductList": []
  }
}

Point is that I want to Serialization to output :

"mdt": {}

Instead of:

"mdt": null

So the question is how can I "mark" this value to be serialized as empty object instead of null or how can it be converted to result in empty object? As I mentioned it is bothering me for some time and I'm not sure how to bite this problem. I tried to change whole problem and change it to be Ignored with

JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}

but the problem is that other side of API must receive empty object, and null or lack of object is treated as error.

As you can see in MDT model, there are mostly bool properties, so whenever I generate object as new() and Ignoring null values it fills all bools with false, generating me an object which is also considered error:

"mdt": {
  "mdtAssetId": null,
  "isMDTDownloaded": false,
  "isNamingConventionCorrect": false,
  "isFolderStructureProvidedByAgencyCorrect": false,
  "heroImageGuidelinesAvailable": false,
  "allImagesAvailable": false,
  "isDesignTargetLocked": false,
  "isPackagingGuidelinesAvailable": false,
  "isRegulatoryGuidelinesAvailable": false,
  "mdtResponse": null,
  "pmaCommentsforMDT": null
}

I'll much appreciate any help or even info it is not possible, but if there's difference between empty and null object I think it is resolvable, but I'm too dumb to figure it out.

TL;DR: I've got object and whenever I'm trying to serialize it to JSON, it's either returning me null, or object with bool values filled as "false", which both are error and I need empty object generated.

Ad

Answer

To avoid the erros just change bool to bool?

public class MDT
{
    [Key]
    public string mdtAssetId { get; set; }
    public bool? isMDTDownloaded { get; set; }
    public bool? isNamingConventionCorrect { get; set; }
}
Ad
source: stackoverflow.com
Ad