Writing a given sequence of int's as an array of hex values in Jackson

空扰寡人 提交于 2019-12-24 07:36:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!