package com.yihu.jw.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;


public class EntityUtils {

    protected static ObjectMapper objectMapper = new ObjectMapper();

    public static <T> T jsonToEntity(String json,Class<T> target){
        T entity = null;
        try {
            entity  = objectMapper.readValue(json,target);
        } catch (Exception e) {
           throw new RuntimeException("Json字符串转换成【"+target.getName()+"】实体类异常：" + e.getMessage());
        }
        return entity;
    }

    public static <T> List<T> jsonToList(String json, Class<T> target)throws Exception{
        com.alibaba.fastjson.JSONArray array = JSON.parseArray(json);
        List<T> list = new ArrayList<>();
        for(int i=0;i<array.size();i++){
            com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject)array.get(i);
            T t = objectMapper.readValue(object.toJSONString(),target);
            list.add(t);
        }
        return list;
    }

}
