Bunny83 / SimpleJSON

A simple JSON parser in C#
MIT License
735 stars 294 forks source link

BUG: AsInt=0 But AsBool=True #52

Open mifth opened 1 year ago

mifth commented 1 year ago

Hi, found one issue. I parsed one json file in Unity and got different results. I'm in a confusion. AsInt=0 But AsBool=True

AsBool should be False!!!!!

My JSON file: TestSV01_NodeTree.zip

My test code of a JSONNode:

Debug.Log(input.GetType());
Debug.Log(input.Value.GetType());
Debug.Log(input.Value["DefaultValue"].GetType());
Debug.Log(input.Value["DefaultValue"].AsInt);
Debug.Log(input.Value["DefaultValue"].AsBool);

My LOG:

System.Collections.Generic.KeyValuePair`2[System.String,BESimpleJSON.JSONNode]
BESimpleJSON.JSONObject
BESimpleJSON.JSONNumber
0
True
Bunny83 commented 1 year ago

Why should it be false? Boolean values in JSON are either "true" or "false". You have a numeric value. SimpleJSON interprets any value that is not false, null or an empty string as true. You can always come up with countless other special cases that may fit your desired interpretation. A number is a double precision float. What values should be false under your interpretation? 0? negative values? positive or negative infinity? NaN?

If you really need this behaviour, feel free to override the AsBool function of the JSONNumber class and implement your desired behaviour. Since every class is declared partial, you can even place this method into a seperate file:

namespace SimpleJSON
{
    public partial class JSONNumber
    {
        public override bool AsBool
        {
            get => m_Data != 0;
            set => m_Data = value?1d:0d;
        }
    }
}

This would interpret any numeric value that is not 0 nor -0 as true. So even NaN or negative infinity would be true.

Though the question is why you want to interpret that object key as boolean when it isn't a boolean. It's a number, so read it as number. JSON is a type aware serialization format. Even C# does not allow an explicit cast from int or double to bool. So why would you expect this behaviour?

int i = 0;
bool b = (bool)i; // Compiler error: Cannot convert type 'int' to 'bool'
double d = 0;
bool b = (bool)d; // Compiler error: Cannot convert type 'double' to 'bool'

While it is common in C / C++ to interpret non zero numeric values as true, this is not the case for C#.