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

io.github.jiawade.tool.utils.GsonUtils Maven / Gradle / Ivy

The newest version!
package io.github.jiawade.tool.utils;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.sun.codemodel.JCodeModel;
import org.jsonschema2pojo.*;
import org.jsonschema2pojo.rules.RuleFactory;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class GsonUtils {
    private static final Gson gson = new GsonBuilder().setLenient().
            registerTypeAdapter(LocalDate.class, new LocalDateAdaptor()).
            registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdaptor()).
            serializeSpecialFloatingPointValues().
            serializeNulls().
            setLenient().
            setPrettyPrinting().
            create();

    public GsonUtils() {

    }

    public static Gson getGson() {
        return gson;
    }

    public static Map parseToMapObject(String jsonString) {
        return gson.fromJson(jsonString, new TypeToken>() {
        }.getType());
    }

    //Type listType = new TypeToken>() {}.getType();
    public static Object parseToObject(String jsonString, Type typeToken) {
        return gson.fromJson(jsonString, typeToken);
    }

    public static Map parseToStringObject(String jsonString) {
        Map map = new HashMap<>();
        parseToMapObject(jsonString).forEach((key, value) -> map.put((String) key, value));
        return map;
    }

    public static  T parseToClass(String jsonString, Class clazz) {
        return gson.fromJson(jsonString, clazz);
    }

    public static  T parseToClass(String jsonString, Type type) {
        return gson.fromJson(jsonString, type);
    }

    public static  List parseToList(String jsonString, List list) {
        return gson.fromJson(jsonString, list.getClass());
    }

    public static  Set parseToSet(String jsonString, Set set) {
        return gson.fromJson(jsonString, set.getClass());
    }

    public static  Collection parseToCollection(String jsonString, Collection collection) {
        return gson.fromJson(jsonString, collection.getClass());
    }

    public static Map parseToStringDouble(String jsonString) {
        Map map = new HashMap<>();
        parseToMapObject(jsonString).forEach((key, value) -> map.put((String) key, (Double) value));
        return map;
    }

    public static Map parseToStringString(String jsonString) {
        Map map = new HashMap<>();
        parseToMapObject(jsonString).forEach((key, value) -> map.put((String) key, (String) value));
        return map;
    }

    public static Map parseToStringLocalDate(String jsonString) {
        Map map = new HashMap<>();
        parseToMapObject(jsonString).forEach((key, value) -> map.put((String) key, LocalDate.parse((String) value)));
        return map;
    }

    public static Map parseToStringLocalDateTime(String jsonString) {
        Map map = new HashMap<>();
        parseToMapObject(jsonString).forEach((key, value) -> map.put((String) key, LocalDateTime.parse((String) value)));
        return map;
    }

    public static String toJsonString(Object clazz) {
        return gson.toJson(clazz);
    }

    public static String toPrettyJsonString(String rawJsonString) {
        JsonElement je = JsonParser.parseString(rawJsonString);
        return gson.toJson(je);
    }

    public static void generateJsonToClass(String json, File outputDirectory, String packageName, String className) {
        JCodeModel jcodeModel = new JCodeModel();
        GenerationConfig config = new DefaultGenerationConfig() {
            @Override
            public boolean isGenerateBuilders() {
                return true;
            }

            @Override
            public SourceType getSourceType() {
                return SourceType.JSON;
            }
        };
        SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new GsonAnnotator(config), new SchemaStore()), new SchemaGenerator());
        try {
            mapper.generate(jcodeModel, className, packageName, json);
            jcodeModel.build(outputDirectory);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private final static class LocalDateAdaptor implements JsonDeserializer, JsonSerializer {
        @Override
        public LocalDate deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) {
            return LocalDate.parse(jsonElement.getAsJsonPrimitive().getAsString());
        }

        @Override
        public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
        }
    }

    private final static class LocalDateTimeAdaptor implements JsonDeserializer, JsonSerializer {
        @Override
        public LocalDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) {
            return LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString());
        }

        @Override
        public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy