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.
SOLUTION:
var serializedJson = JsonConvert.SerializeObject (SomeBoolObject, new JsonSerializerSettings {
DefaultValueHandling = DefaultValueHandling.Include
});
LIVE DEMO LINK
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;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With