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
CodePudding user response:
The premise of the question is incorrect; PropertyInfo.GetValue works just fine - here used with your method with zero changes:
static void Main()
{
var obj = new Foo { Bar = true, Blap = false };
var sb = new StringBuilder();
AppendObjectPropertiesInJson(sb, obj);
Console.WriteLine(sb);
}
class Foo
{
public bool Bar { get; set; }
public bool Blap { get; set; }
}
outputs the almost-JSON:
{
"Bar": true,
"Blap": false,
},
Note that the expression value = (bool)value is a redundant unbox box, but: it doesn't change any results (just: it doesn't do anything useful, either).
Note that we can show native bool here too:
else if (type == typeof(bool))
{
var typed = (bool)value;
Console.WriteLine(typed ? "it was true" : "it was false");
// ...content.Append(" \"" name "\": " value.ToString().ToLower() ",\n");
}
If you have an example where PropertyInfo.GetValue doesn't work, then post that example. Additionally, note that writing your own JSON output is not recommended, as is very easy to get wrong.
