package com.izouma.nineth.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonUtils {
    final static String defaultDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";


    public static class Builder {
        private Map<String, Object> map = new HashMap<>();

        public String build() {
            return new JSONObject(map).toJSONString();
        }

        public Builder add(String key, Object value) {
            map.put(key, value);
            return this;
        }
    }

    public static class ArrayBuilder {
        private List<Object> list = new ArrayList<>();

        public String build() {
            return new JSONArray(list).toString();
        }

        public ArrayBuilder add(Object object) {
            list.add(object);
            return this;
        }
    }

    public static <T> String serialize(T t) {
        JSON.DEFFAULT_DATE_FORMAT = defaultDateFormat;
        return serialize(t, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
    }

    public static <T> String serialize(T t, SerializerFeature... features) {
        return JSON.toJSONString(t, features);
    }

    public static <T> T deSerialize(String string, Class<T> tClass) {
        return JSON.parseObject(string, tClass);
    }

    public static <T> List<T> deSerializeList(String string, Class<T> tClass) {
        return JSON.parseArray(string, tClass);
    }

    public static <T> T complexJsonToObject(String jsonString) {
        return JSON.parseObject(jsonString, new TypeReference<T>() {
        }.getType());
    }
}
