40

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 my data this is my sample code:

    JSONObject obj = new JSONObject();
    obj.put("name", "foo");
    obj.put("num", new Integer(100));
    obj.put("balance", new Double(1000.21));
    obj.put("is_vip", new Boolean(true));
    obj.put("nickname",null);

    sendData = obj.getBytes(); //this is error because not have methos getBytes();

i know my problem but i can't found how to convert json object to byte, any suggestion ?

0

4 Answers 4

53

Get the bytes of the string:

obj.toString().getBytes(theCharset);
Sign up to request clarification or add additional context in comments.

3 Comments

getBytes should be passed an encoding. Otherwise ... no fun when it isn't the assumed "default encoding".
Check my answer bellow to see how to avoid unnecessary conversion to a String and additional encoding based on the provided charset: stackoverflow.com/a/39412196/3114959
JSONObject and an a String both are different representations of data. What we see in notepads is String representation of JSON Data, not the actual data. For example if you see an int value 65535 in your notepad, this is actually a string of characters 6,5,5,3 and 5 (five characters = 5*2 bytes = 10 bytes in java) , rather a single int value 65535 (4 bytes in java).
35

Assuming the JSONObject you mention is from this, you can get the bytes like below

sendData = obj.toString().getBytes("utf-8");

2 Comments

yes you right too...:) so i give some up in each answer ...:)
@Agung the link is no longer valid, can you tell what is the use if this ?
3

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).

2 Comments

Json.createWriter(stream).write(obj); The above line only takes Javax.json type obj and not JSONObject (which is mentioned in the question). If you try to cast it like : Json.createWriter(stream).write((JSONObject)obj); It throws exception : cannot cast. Any suggestions for JSONObject type object.
where is Json coming from?
3

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>

1 Comment

Oh! I missed to use objectMapper after knowing it..., I have updated my code though. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.