简体   繁体   English

将 JSON 类型转换为 java 中的字节数组格式

[英]convert JSON Type to Byte array format in java

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:当我想在 UDP 协议中使用字节格式发送数据时遇到问题,问题是当我尝试创建类型为 json object 的数据时,我无法获取数据的字节格式这是我的示例代码:

    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?我知道我的问题,但我找不到如何将 json object 转换为字节,有什么建议吗?

Get the bytes of the string:获取字符串的字节:

obj.toString().getBytes(theCharset);

Assuming the JSONObject you mention is from this , you can get the bytes like below假设您提到的 JSONObject 来自于此,您可以获得如下字节

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 ):为了避免从Stringbyte[]的不必要的转换,后者强制基于提供的charset进行编码,我更喜欢直接将JsonWriterByteArrayOutputStream一起使用(例如JsonValue子类型将JsonWriterStringWriter一起使用):

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).您至少需要 3 个(考虑到您省略了调用JsonWriter.close()的事实,这在这种情况下是不必要的)。

Use utility class from ObjectMapper of jackson-databind project, ie objectMapper.writeValueAsBytes(dto) returns byte[]使用jackson-databind项目的ObjectMapper中的实用程序 class,即objectMapper.writeValueAsBytes(dto)返回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: Maven 依赖:

<!-- 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM