convert JSON Type to Byte array format in java

前端 未结 4 780
萌比男神i
萌比男神i 2021-02-05 02:25

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

4条回答
  •  故里飘歌
    2021-02-05 02:44

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

提交回复
热议问题