package com.emr.util;

import com.alibaba.fastjson.JSON;
import com.emr.vo.SelectEntity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/12/2 14:34
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/12/2 14:34
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class ConvertToSelectJson {
    public static String toSelectJson(List dataList, String value, String name)throws Exception{
        List<SelectEntity> list = new ArrayList<>();
        if(null != dataList && !dataList.isEmpty()){
            for (int i = 0; i < dataList.size(); i++) {
                SelectEntity selectEntity = new SelectEntity();
                //传送value值
                selectEntity.setValue(getValueByDeclaredField(dataList.get(i),value));
                selectEntity.setName(getValueByDeclaredField(dataList.get(i),name));
                list.add(selectEntity);
            }
        }
        return JSON.toJSONString(list);
    }
    //根据反射获取属性值
    private static String getValueByDeclaredField(Object obj,String fieldName)throws Exception{
        Field valueField = obj.getClass().getDeclaredField(fieldName);
        valueField.setAccessible(true);
        return valueField.get(obj).toString();
    }
}
