将给定的 int 序列写入 Jackson 中的十六进制值数组
Writing a given sequence of int's as an array of hex values in Jackson
是否可以使 Jackson FasterXML
库将给定的 Integer
值序列序列化为 Hex
值的数组?也就是说,简单地说,我想要代码:
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]
。
要回答这个问题,我们需要看一下 JSON
specification 以及它对数字的看法:
A number is very much like a C or Java number, except that the octal
and hexadecimal formats are not used.
因此,要以十六进制格式写入数字,您需要实现自定义序列化程序并将它们写入 string
原语:
["0x1","0x2","0x10","0x10"]
是否可以使 Jackson FasterXML
库将给定的 Integer
值序列序列化为 Hex
值的数组?也就是说,简单地说,我想要代码:
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]
。
要回答这个问题,我们需要看一下 JSON
specification 以及它对数字的看法:
A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.
因此,要以十六进制格式写入数字,您需要实现自定义序列化程序并将它们写入 string
原语:
["0x1","0x2","0x10","0x10"]