package com.xhpc.evcs.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class JSONUtil {

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final Logger logger = LoggerFactory.getLogger(JSONUtil.class);

    /**
     * 将一个对象转换成目标对象
     *
     * @param src
     * @param dest
     * @return
     */
    public static <T> T copyProperties(Object src, Class<T> dest) throws Exception {

        return JSON.parseObject(JSON.toJSONString(src), dest);
    }

    public static <T> T copyProperties(Object src, JavaType type) throws Exception {

        return JSON.parseObject(JSON.toJSONString(src), type);
    }

    // 适用于简单对象,复杂对象参考下面的main方法
    public static <T> T readParams(String params, Class<T> clz) {

        try {
            return mapper.readValue(params, clz);
        } catch (JsonProcessingException e) {
            logger.debug("invalid json:{}", params);
            return null;
        }
    }

    public static <T> List<T> readParamsList(String data, Class<T> clzo) throws IOException {

        CollectionType javaType = mapper.getTypeFactory()
                .constructCollectionType(List.class, clzo);
        return mapper.readValue(data, javaType);
    }

    public static String toJSONString(Object o) throws JsonProcessingException {

        return mapper.writeValueAsString(o);
    }

    // 适用于复杂对象的例子
    public static void main(String[] args) throws IOException {

        String json = "[\n" + "{\n" + "  \"id\": \"123\",\n" + "  \"phoneNumbers\": [1,2],\n  \"gf\": {\"id\":\"1\"," +
                "\"name\":\"nana\"}\n" + "}\n" + "\n]";
        byte[] jsonData = json.getBytes();
        ObjectMapper objectMapper = new ObjectMapper();
        //read JSON like DOM Parser
        JsonNode rootNode = objectMapper.readTree(jsonData);
        JsonNode idNode = rootNode.path("id");
        System.out.println("id = " + idNode.asInt());

        JsonNode phoneNosNode = rootNode.path("phoneNumbers");
        Iterator<JsonNode> elements = phoneNosNode.elements();
        while (elements.hasNext()) {
            JsonNode phone = elements.next();
            System.out.println("Phone No = " + phone.asLong());
        }
        JsonNode gfid = rootNode.path("gf").path("id");
        System.out.println("gf id: " + gfid.asInt());







    }

}
