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

io.github.simplefixture.utils.JsonUtils Maven / Gradle / Ivy

There is a newer version: 1.0.0-rc
Show newest version
package io.github.simplefixture.utils;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JsonUtils {

    public static  Object create(String json, Class clazz){
        return new GsonBuilder()
                .registerTypeAdapter(Date.class, new DateDeserializer())
                .create().fromJson(json, clazz);
    }
}

class DateDeserializer implements com.google.gson.JsonDeserializer {

    @Override
    public Date deserialize(JsonElement element, Type type, JsonDeserializationContext context) {

        ThreadLocal df = ThreadLocal.withInitial(()->new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        String el = element.getAsString();
        Date convertedDate;
        try {
            if(StringUtils.isNumeric(el)){
                convertedDate = new Date(new Timestamp(Long.parseLong(el)).getTime());
            }else{
                convertedDate = df.get().parse(el);
            }
        } catch (Exception e) {
            SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy hh:mm:ss a");
            try {
                convertedDate = sdf.parse(el);
            } catch (ParseException ex) {
                throw new RuntimeException("DateType value is Not valid", e);
            }
        }
        return convertedDate;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy