How to conver cbor to json in java

in #developement4 years ago (edited)

Concise Binary Object Representation (CBOR) is a binary data serialization format loosely based on JSON.

Sometimes (common in blockchain) data is encoded with cbor and the client is expecting json.

If you want to convert cbor to json in java maven project -

  1. Add to your pom.xml

com.fasterxml.jackson.core
jackson-core version 2.11.0

And

com.fasterxml.jackson.dataformat
jackson-dataformat-cbor same version as core

  1. Add this function:

protected static String cborToJson(byte[] input) throws IOException {
CBORFactory cborFactory = new CBORFactory();
CBORParser cborParser = cborFactory.createParser(input);
JsonFactory jsonFactory = new JsonFactory();
StringWriter stringWriter = new StringWriter();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter);
while (cborParser.nextToken() != null) {
jsonGenerator.copyCurrentEvent(cborParser);
}
jsonGenerator.flush();
return stringWriter.toString();
}

For more examples
https://www.programcreek.com/java-api-examples/?api=com.fasterxml.jackson.dataformat.cbor.CBORFactory

Hope thats helpful