convert JSON Type to Byte array format in java

98,980

Solution 1

Get the bytes of the string:

obj.toString().getBytes(theCharset);

Solution 2

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

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

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

Solution 4

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>
Share:
98,980
viyancs
Author by

viyancs

i'm software enginer with experience in web application ,network programming and mobile application.

Updated on April 28, 2020

Comments

  • viyancs
    viyancs about 4 years

    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 ?

  • Admin
    Admin about 12 years
    getBytes should be passed an encoding. Otherwise ... no fun when it isn't the assumed "default encoding".
  • viyancs
    viyancs about 12 years
    yes you right too...:) so i give some up in each answer ...:)
  • Stepan Vavra
    Stepan Vavra almost 8 years
    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
  • Derick Daniel
    Derick Daniel about 6 years
    @Agung the link is no longer valid, can you tell what is the use if this ?
  • balajimore
    balajimore about 6 years
    Oh! I missed to use objectMapper after knowing it..., I have updated my code though. thanks.
  • Manishoaham
    Manishoaham almost 5 years
    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).
  • Sdembla
    Sdembla about 4 years
    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.
  • Harry Theo
    Harry Theo over 2 years
    where is Json coming from?