简体   繁体   中英

Java MessagePack null check

I am trying to get familar with Messagepack for Java .

I get the data via Mqtt. If the variable is not null everything is fine but the variable can also be null and in this case I will get this Exception: Expected Int, but got Nil (c0)

MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(m.getPayload());
int someInt              = unpacker.unpackInt();
String someString        = unpacker.unpackString();

So far I was not able to figure out how to get NULL back I want to avoid to use TRY/CATCH so currently I am using this way

int someInt = unpacker.getNextFormat().equals("NIL") ? unpacker.unpackInt() : null;

Is there a better way ?

I looked the javadoc of MessageUnpacker and it doesn't seem provide a better way.

The example code is very close of your way :

 MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(...);
 while(unpacker.hasNext()) {
     MessageFormat f = unpacker.getNextFormat();
     switch(f) {
         case MessageFormat.POSFIXINT:
         case MessageFormat.INT8:
         case MessageFormat.UINT8: {
            int v = unpacker.unpackInt();
            break;
         }
         case MessageFormat.STRING: {
            String v = unpacker.unpackString();
            break;
         }
         // ...
   }
 }

So I think that you are in the good path.
But if you repeat this retrieval multiple times(and it is very likely), you could introduce utility methods that does the job for you.

For example for unpackInt() :

public Integer unpackIntOrNull (MessageUnpacker unpacker){
    return unpacker.getNextFormat() == MessageFormat.INT8 ?
           unpacker.unpackInt() : null; 
}

And now, it is very straight to unpack elements :

Integer einInt = unpackIntOrNull(unpacker);
Integer einAndereInt = unpackIntOrNull(unpacker);
...

MessageUnpacker has a method named tryUnpackNil . If the next byte is a nil value, this method reads it and returns true , otherwise reads nothing and returns false .

This can be used to skip over nil values, and unpack non-nil values with eg:

final MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(data);
final Integer value = unpacker.tryUnpackNil() ? null : unpacker.unpackInt();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM