Similar to PropertyInfo.GetValue on Boolean is always True although no useful answer was posted.
I'm using Entity Framework to gather objects from a database and I'm trying to create Json structures as strings. However when gathering boolean answers in the same way as other types, the boolean always returns true.
I've tried to cast the value to a boolean here but I originally tried using the same method as other types (just using value). Is there a reason for this or a fix? Thanks
private static void AppendObjectPropertiesInJson(StringBuilder content, Object obj)
{
content.Append(" {\n");
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
var type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
var name = propertyInfo.Name;
var value = propertyInfo.GetValue(obj, null);
if (value == null)
content.Append(" \"" + name + "\": null,\n");
// Error, always returns true
else if (type == typeof(bool))
{
value = (bool)value;
content.Append(" \"" + name + "\": " + value.ToString().ToLower() + ",\n");
}
else if (type == typeof(int))
content.Append(" \"" + name + "\": " + value.ToString().ToLower() + ",\n");
else if (type == typeof(string))
content.Append(" \"" + name + "\": " + "\"" + value.ToString() + "\",\n");
// TODO: Handle arrays
}
content.Append(" },\n");
}
edit: Issue was with unexpected changes in database. Thanks to everybody who helped show there was no issue with this code