All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.meixuesong.aggregatepersistence.JsonComparator Maven / Gradle / Ivy

There is a newer version: 1.2.3
Show newest version
package com.github.meixuesong.aggregatepersistence;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;
import java.text.SimpleDateFormat;

public class JsonComparator implements PropertyComparator {
    private ObjectMapper mapper;

    @Override
    public  boolean isAllPropertiesEqual(T a, T b) {
        String jsonA = getJson(a);
        String jsonB = getJson(b);

        return jsonB.equals(jsonA);
    }


    private  String getJson(T object) {
        try {
            return getMapper().writeValueAsString(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private synchronized ObjectMapper getMapper() {
        if (mapper == null) {
            createObjectMapper();
        }

        return mapper;
    }

    private void createObjectMapper() {
        if (this.mapper == null) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
            mapper.registerModule(new JavaTimeModule());
            mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

            this.mapper = mapper;
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy