I have a problem when I want to sending data using byte format in UDP protocol, the problem is when I try to create a data with type json object, I can\'t get the byte format of
To avoid unnecessary conversion from String
to byte[]
which enforces encoding based on the provided charset, I prefer to use JsonWriter
directly with ByteArrayOutputStream
for instance (JsonValue
subtypes use JsonWriter
with StringWriter
):
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Json.createWriter(stream).write(obj);
byte[] sendData = stream.toByteArray()
System.out.println("Bytes array: " + sendData);
System.out.println("As a string: " + stream.toString());
Additionally, one can even enable pretty printing as follows:
Json.createWriterFactory(
Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true))
.createWriter(stream)
.write(obj);
The only sad thing is that it's not an one-liner. You'd need 3 at least (given the fact that you omit calling JsonWriter.close()
which is unnecessary in this context).