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
Assuming the JSONObject you mention is from this, you can get the bytes like below
sendData = obj.toString().getBytes("utf-8");
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).
Use utility class from ObjectMapper
of jackson-databind
project, ie objectMapper.writeValueAsBytes(dto)
returns byte[]
@Autowired
private ObjectMapper objectMapper;
ContractFilterDTO filter = new ContractFilterDTO();
mockMvc.perform(post("/api/customer/{ico}", "44077866")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(objectMapper.writeValueAsBytes(filter)))...
Maven dependency:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8.1</version>
</dependency>
Get the bytes of the string:
obj.toString().getBytes(theCharset);