Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON serializer - when boolean value set to false key is missing on frontend

I have a webapi (ASP.Net Core) + frontend app (Angular). I'm passing some data that are stored in a json file on disk from the backend to frontend. On the frontend, for boolean properties, I'm missing them if the value was set to false. Using Newtonsoft.JSON.

Let say I have the following class:

public class Element<T>
{
    public Element(T value, T defaultValue, string name)
    {
        Value = value;
        DefaultValue = defaultValue;
        TypeName = name
    }
public T Value { get; set; }
public T DefaultValue { get; set; }
public string TypeName { get; set;}
}

Object creation:

public class Setting
{
    public Element<bool> SomeBoolObject { get; set; } = new Element<bool>(false, false, "boolean");
}

JSON file on disk:

"SomeBoolObject": {
"value": false,
"defaultvalue": false,
"typename": "boolean"
}

And then on frontend I have only

{
    "SomeBoolObject": {
    "typeName": "Boolean"
    }
}

The Value and DefaultValue keys are missing from the object, but only when value is set to false. When I set it to true then on frontend I got all keys and values:

"SomeBoolObject": {
"value": true,
"defaultvalue": true,
"typename": "boolean"
}

And on frontend:

{
    "SomeBoolObject": {
    "value": 1,
    "defaultValue": 1,  
    "typeName": "Boolean"
    }
}

What could be the reason of such behavior? Do I need to write some custom serializer for handling "false" values?

This is kind of similar to Json.net DefaultValueHandling exempting boolean alone

But the proposed solution did not work for me.

like image 800
beribazoo Avatar asked Jan 20 '26 06:01

beribazoo


2 Answers

SOLUTION:

var serializedJson = JsonConvert.SerializeObject (SomeBoolObject, new JsonSerializerSettings {
  DefaultValueHandling = DefaultValueHandling.Include
});

LIVE DEMO LINK

like image 60
Naveen Kumar V Avatar answered Jan 22 '26 20:01

Naveen Kumar V


I tackle the issue with adding some attributes for properties:

public class Element<T>
{
    public Element(T value, T defaultValue, string name)
    {
        Value = value;
        DefaultValue = defaultValue;
        TypeName = name
    }
    [JsonProperty(Required = Required.Always)]
    public T Value { get; set; }
    [JsonProperty(Required = Required.Always)]
    public T DefaultValue { get; set; }
    public string TypeName { get; set;}
}
like image 23
beribazoo Avatar answered Jan 22 '26 18:01

beribazoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!