Thursday, 28 November 2019

How to stringify JSON for hashing and easy comparison in Java?

Or how to implement https://github.com/substack/json-stable-stringify in Java?
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;

    public static void stringify(final String jsonPath) throws Exception {
        final byte[] bytes = Files.readAllBytes(Paths.get(jsonPath));
        final String jsonData = new String(bytes);

        ObjectMapper om = new ObjectMapper();
        om.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
        Map map = om.readValue(jsonData, HashMap.class);
        String json = om.writeValueAsString(map);
    }

No comments:

Blog Archive