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对象创建数据时,我无法得到我的数据的字节格式这是我的示例代码:
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对象转换为字节,任何建议?
4 个解决方案
#1
28
Get the bytes of the string:
获取字符串的字节:
obj.toString().getBytes(theCharset);
#2
25
Assuming the JSONObject you mention is from this, you can get the bytes like below
假设您提到的JSONObject来自于此,您可以获得如下所示的字节
sendData = obj.toString().getBytes("utf-8");
#3
2
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
):
为了避免从String到byte []的不必要转换,它基于提供的字符集强制执行编码,我更喜欢直接使用JsonWriter和ByteArrayOutputStream(JsonValue子类型使用带有StringWriter的JsonWriter):
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()的事实,这在这个上下文中是不必要的)。
#4
2
Use utility class from ObjectMapper
of jackson-databind
project, ie objectMapper.writeValueAsBytes(dto)
returns byte[]
使用来自jackson-databind项目的ObjectMapper的实用程序类,即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>
#1
28
Get the bytes of the string:
获取字符串的字节:
obj.toString().getBytes(theCharset);
#2
25
Assuming the JSONObject you mention is from this, you can get the bytes like below
假设您提到的JSONObject来自于此,您可以获得如下所示的字节
sendData = obj.toString().getBytes("utf-8");
#3
2
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
):
为了避免从String到byte []的不必要转换,它基于提供的字符集强制执行编码,我更喜欢直接使用JsonWriter和ByteArrayOutputStream(JsonValue子类型使用带有StringWriter的JsonWriter):
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()的事实,这在这个上下文中是不必要的)。
#4
2
Use utility class from ObjectMapper
of jackson-databind
project, ie objectMapper.writeValueAsBytes(dto)
returns byte[]
使用来自jackson-databind项目的ObjectMapper的实用程序类,即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>