问题
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...");
}
}
}
would produce [0x1,0x2,0x10,0x10]
, not [1,2,16,32]
as it does now.
回答1:
To answer this question we need to take a look at JSON specification and what it says about numbers:
A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.
So, to write numbers in hexadecimal format you need to implement custom serialiser and write them as string
primitives:
["0x1","0x2","0x10","0x10"]
来源:https://stackoverflow.com/questions/57452900/writing-a-given-sequence-of-ints-as-an-array-of-hex-values-in-jackson