在Jackson中将给定的int序列编写为十六进制值数组 [英] Writing a given sequence of int's as an array of hex values in Jackson
本文介绍了在Jackson中将给定的int序列编写为十六进制值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使Jackson FasterXML
库将给定的Integer
值序列序列化为Hex
值数组?简而言之,我想要代码:
Is it possible to make Jackson FasterXML
library to serialize a given sequence of Integer
values as an array of Hex
values? That is, simply put, I would like that the code:
public class SampleJson {
private final ObjectMapper mapper = new ObjectMapper();
JsonNode toJson(int[] values) {
ArrayNode jsonArray = mapper.createArrayNode();
for(int i: values)
jsonArray.add(i);
return jsonArray;
}
String toJsonString(JsonNode node) throws JsonProcessingException {
return mapper.writeValueAsString(node);
}
public static void main(String[] args) {
SampleJson sj = new SampleJson();
int[] values = {1, 2, 0x10, 0x20};
try {
System.out.println(sj.toJsonString(sj.toJson(values)));
} catch (JsonProcessingException e) {
System.err.println("Something goes wrong...");
}
}
}
会产生[0x1,0x2,0x10,0x10]
,而不是现在的[1,2,16,32]
.
would produce [0x1,0x2,0x10,0x10]
, not [1,2,16,32]
as it does now.
推荐答案
要回答此问题,我们需要看一下 JSON
规范及其对数字的说明:
To answer this question we need to take a look at JSON
specification and what it says about numbers:
数字非常类似于C或Java数字,除了八进制 和十六进制格式.
因此,要以十六进制格式写数字,您需要实现自定义序列化程序并将其写为string
原语:
So, to write numbers in hexadecimal format you need to implement custom serialiser and write them as string
primitives:
["0x1","0x2","0x10","0x10"]
这篇关于在Jackson中将给定的int序列编写为十六进制值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文