当我想在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();
我知道我的问题,但我找不到如何将json对象转换为byte,任何建议?
答案 0 :(得分:33)
获取字符串的字节:
obj.toString().getBytes(theCharset);
答案 1 :(得分:28)
假设您提到的JSONObject来自this,您可以获得如下所示的字节
sendData = obj.toString().getBytes("utf-8");
答案 2 :(得分:3)
为了避免从基于提供的字符集强制执行编码的String
到byte[]
进行不必要的转换,我更倾向于JsonWriter
直接使用ByteArrayOutputStream
例如(JsonValue
子类型使用JsonWriter
与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());
此外,甚至可以按如下方式启用漂亮打印:
Json.createWriterFactory(
Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true))
.createWriter(stream)
.write(obj);
唯一可悲的是,它不是单行。你至少需要3个(考虑到你省略了调用JsonWriter.close()
这个在这种情况下不必要的事实。)
答案 3 :(得分:2)
使用来自ObjectMapper
项目的jackson-databind
的实用工具类,即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依赖:
<!-- 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>