Null type mismatch help

So im checking for null but still getting an error… trying in two different ways here:
Null type mismatch (type annotations): required ‘org.openhab.binding.sonoff.internal.api.@NonNull Switch’ but this expression has type ‘org.openhab.binding.sonoff.internal.api.@Nullable Switch’

List<Switch> switches = new ArrayList<>();

        if (device.getParams().getSwitches().get(0).getSwitch() != null) {

            switches.add(gson.fromJson("{switch:" + device.getParams().getSwitches().get(0).getSwitch() + ",outlet: 0}",

                    Switch.class));

        } else {

            switches.add(gson.fromJson("{switch:" + "off" + ",outlet: 0}", Switch.class));

        }

        switches.add(gson.fromJson("{switch:" + device.getParams().getSwitches().get(1).getSwitch() != null

                ? device.getParams().getSwitches().get(1).getSwitch()

                : "off" + ",outlet: 1}", Switch.class));

I think that’s because gson.fromJson() is annotated with @Nullable. Why do you create a json string just to decode it again? Why not just create an instance of the Switch class directly with the correct parameters?

Two subsequent calls of a method are not guaranteed to return the same result. Assign to a local variable, check that for non-null and use it instead of calling the second time.

Then you can be sure that the Input to fromJson Is non-null (and the result is also non-null). The checker can’t know that, but you can use Objects.requireNonNull, which guarantees the return value to be non-null.

Edit: I agree that you should not create a JSON-strong to decode it to create an object. Create the Object directly.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.