4

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

Joe Arnold
  • 43
  • 5
  • post your object and how you call this function and also post your result. because it seems reflection should work for boolean as well as for other types – sa-es-ir Jan 10 '22 at 13:31
  • Your code doesnt appear to have any problems with false bools: https://dotnetfiddle.net/m9ntlM – Jamiec Jan 10 '22 at 13:34
  • 3
    I do wonder why you're hand crafting JSON also, when JSON serializers (of many types) exist – Jamiec Jan 10 '22 at 13:35
  • @SaeedEsmaeelinejad this has been the same result for multiple objects. All created in Entity Framework from my database – Joe Arnold Jan 10 '22 at 13:53
  • @Jamiec this may be the easiest way to fix, although it would be nice to see why this wasn't working for me – Joe Arnold Jan 10 '22 at 13:53
  • 1
    @JoeArnold Unless you can provide a [mcve] demonstrating the problem Im not sure we can tell you - as you can see in my dotnetfiddle link it appears to work just fine – Jamiec Jan 10 '22 at 13:56
  • using json serializer is not easiest way but that is the best way because that is error safe! and as @Jamiec said your current code is working maybe the problem is some where else. – sa-es-ir Jan 10 '22 at 13:59
  • @Jamiec will do – Joe Arnold Jan 10 '22 at 14:04

1 Answers1

1

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900