package com.xydl.cac.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.File;
import java.io.IOException;
import java.util.Map;


public class JSONUtil {

    private static JSONProcessor jSONProcessor = new JSONProcessor();

    public static String object2Json(Object obj) {
        return jSONProcessor.buildJSONFromJSONObject(obj);
    }

    public static String object2Json(Object obj, boolean prettyPrinter) {
        return jSONProcessor.buildJSONFromJSONObject(obj, prettyPrinter);
    }

    public static <T> T json2Object(String json, Class<T> clazz) throws Exception {
        return jSONProcessor.buildJSONObjectFromJSON(json, clazz);
    }

    public static <T> T file2Object(File file, Class<T> clazz) throws Exception {
        return jSONProcessor.buildJSONObjectFromJSON(file, clazz);
    }

    public static Map<String, Object> object2Map(Object obj) {
        try {
            return jSONProcessor.fromJSON2Map(obj);
        } catch (IOException e) {
            return null;
        }
    }

    public static String object2Xml(Object obj) throws JsonProcessingException {
        XmlMapper xmlMapper = XmlMapper.builder()
                .enable(SerializationFeature.INDENT_OUTPUT)
                .build();
        return xmlMapper.writeValueAsString(obj);
    }

    public static <T> T xml2Object(String xml, Class<T> clazz) throws JsonProcessingException {
        XmlMapper xmlMapper = XmlMapper.builder()
                .build();
        return xmlMapper.readValue(xml, clazz);
    }

    public static JsonNode xml2JsonNode(String xml) throws JsonProcessingException {
        XmlMapper xmlMapper = XmlMapper.builder()
                .build();
        return xmlMapper.readTree(xml);
    }

}
