convert JSON Type to Byte array format in java

前端 未结 4 772
萌比男神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:38

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

    sendData = obj.toString().getBytes("utf-8");
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-02-05 02:51

    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>
    
    0 讨论(0)
  • 2021-02-05 02:53

    Get the bytes of the string:

    obj.toString().getBytes(theCharset);
    
    0 讨论(0)
提交回复
热议问题