Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: AsInt=0 But AsBool=True #52

Open
mifth opened this issue Nov 26, 2022 · 1 comment
Open

BUG: AsInt=0 But AsBool=True #52

mifth opened this issue Nov 26, 2022 · 1 comment

Comments

@mifth
Copy link

mifth commented Nov 26, 2022

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
Copy link
Owner

Bunny83 commented Nov 26, 2022

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#.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants