[SOLVED] Java: How to read binary cloudevent

Issue

This Content is from Stack Overflow. Question asked by Pierre

I want to process binary cloudevents in a java kafka consumer. How do i get back the playload values from binary?

so far i have:

while (true) {
    ConsumerRecords<String, CloudEvent> records =
            consumer.poll(Duration.ofMillis(100));

    for (ConsumerRecord<String, CloudEvent> record : records) {
        CloudEventData data = record.value().getData();
        System.out.println(data.toString());
    }
}

which just logs
BytesCloudEventData{value=[123, 34, 112, 114, 105, 99, 101, 34, 58, 49, 57, 53, 48, 51, 46, 56, 51, 44, 34, 116, 105, 109, 101, 115, 116, 97, 109, 112, 34, 58, 49, 46, 54, 54, 51, 53, 51, 54, 48, 54, 50, 55, 50, 50, 54, 50, 52, 69, 57, 125]}



Solution

The "binary" example you gave is already a JSON string:

value=[123, 34, 112, 114, 105, 99, 101, 34, 58, 49, 57, 53, 48, 51,
46, 56, 51, 44, 34, 116, 105, 109, 101, 115, 116, 97, 109, 112, 34,
58, 49, 46, 54, 54, 51, 53, 51, 54, 48, 54, 50, 55, 50, 50, 54, 50,
52, 69, 57, 125]

ASCII text: {"price":19503.83,"timestamp":1.663536062722624E9}

SUGGESTION: try something like this:

String s = new String(bytes, StandardCharsets.UTF_8);


This Question was asked in StackOverflow by Pierre and Answered by paulsm4 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?