package com.usoft.credit.util;

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

import java.util.*;

/**
 * created by shicr on 2018/6/7
 **/
public abstract class FlexJsonUtils {
    public static <T> T fromJson(String json, Class<T> cls) {
        return new JSONDeserializer<T>().use(null, cls).deserialize(json);
    }

    public static <K, V> Map<K, V> fromJson(String json) {
        Map<K, V> map = new HashMap<K, V>();
        return new JSONDeserializer<Map<K, V>>().use(null, map.getClass()).deserialize(json);
    }

    public static <K, V> LinkedHashMap<K, V> fromLinkedJson(String json) {
        Map<K, V> map = new LinkedHashMap<K, V>();
        return new JSONDeserializer<LinkedHashMap<K, V>>().use(null, map.getClass()).deserialize(json);
    }

    public String toJson() {
        return new JSONSerializer().exclude("*.class").serialize(this);
    }

    public static String toJson(Object obj) {
        return new JSONSerializer().exclude("*.class").serialize(obj);
    }

    public static String toJsonDeep(Object obj) {
        return new JSONSerializer().exclude("*.class").deepSerialize(obj);
    }

    public static <T> String toJsonArray(Collection<?> collection) {
        return new JSONSerializer().exclude("*.class").serialize(collection);
    }

    public static <T> List<T> fromJsonArray(String json, Class<?> cls) {
        return new JSONDeserializer<List<T>>().use(null, ArrayList.class).use("values", cls).deserialize(json);
    }

    public static <T> Map<String,T> fromJsonHashMap(String json, Class<?> cls) {
        return new JSONDeserializer<Map<String,T>>().use(null, HashMap.class).use("values", cls).deserialize(json);
    }
}
