Java - How decode CBOR encoded byte[] array?

5.6k views Asked by At

I get data from server - is a CBOR encoded byte[] array and to decoded this I am using cbor-java implementation.

    byte[] decodedMessage = { 0x78, (byte)0x9c, 0x5b, (byte)0xe4, 0x58, 0x10}
    ByteArrayInputStream bais = new ByteArrayInputStream(decodedMessage);
    List<DataItem> dataItems = new CborDecoder(bais).decode();
    for(DataItem dataItem : dataItems) {
    }

If you have some experience with this, can you explain me how i can get the decoded content of array, not the DataItem object.

2

There are 2 answers

0
Absurd-Mind On BEST ANSWER

The DataItem is already very close to what you want. First you need to check which type the DataItem is:

for (DataItem dataItem : dataItems) {
    System.out.println("the type of this dataItem is " + dataItem.getMajorType());
    switch(dataItem.getMajorType()) {
        UNSIGNED_INTEGER:
            UnsignedInteger unsignedInteger = (UnsignedInteger) dataItem;
            System.out.println("the value of this dataItem is " + unsigendInteger.getValue());
        /* ... add missing ones */
        default:
            System.out.println("unknown type: " + dataItem.getMajorType());
    }
}

With that you can read the data that is inside your byte array. You just need to adapt it for the values you need it.

0
AudioBubble On

Have you considered using jackson-dataformats-binary? The library has very good performance and is just like working with JSON.