Convert ints to booleans

后端 未结 2 1912
北海茫月
北海茫月 2021-02-01 04:32

Is there a way that I can convert int/short values to booleans? I\'m receiving JSON that looks like this:

{ is_user: \"0\", is_guest: \"0\" }

I

2条回答
  •  一整个雨季
    2021-02-01 05:15

    If you're reading them in as ints or shorts, then you can just

    boolean b = (i != 0)
    

    Where b is the boolean you want to get and i is the int or short value.

    If you're reading them in as Strings then you want

    boolean b = !s.equals("0"); // use this if you WANT null pointer exception
                                // if the string is null, useful for catching
                                // bugs
    

    or

    boolean b = !"0".equals(s); // avoids null pointer exception, but may silently
                                // let a bug through
    

提交回复
热议问题