java中list集合、map集合、String数组、JSONObject、实体类、JSON字符串、JSON数组之间的转换,常用类型转换---工具类

list集合转换String[ ] 数组

List list = new ArrayList<>();
String[] strings = list.toArray(new String[list.size()]);

String[ ] 转换 数组list集合

//准备一个String数组
String[] strs = {"aa","bb","cc"};

//String数组转List
方法1: 
Listring> strsToList1= Arrays.asList(strs);

方法2:
List strsToList2=new ArrayList<>();
Collections.addAll(strsToList2,strs);

方法3:
List strsToList3=new ArrayList<>();
    for(String s:strs){
    strsToList3.add(s);
}

String转JSON对象

String result =“123456”
JSONObject jsonObject = JSON.parseObject(result);

通过 net.sf.json.JSONObject 转换工具需要配置 maven 下载jar包, maven配置

<dependency>
<groupld>et.st.jon-lib</groupld>
<artifactld>json-lib</artifactld>
<version>2.4</version>
<classifer>jdk15</classifier>
</dependency>

将实体类转换JSONObject JSON对象

net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(warningInfoEntity);

将String转换json对象

net.sf.json.JSONObject jsonObject1 = net.sf.json.JSONObject.fromObject(string);

将对象转换实体类

WarningInfoEntity warningInfoEntity =(WarningInfoEntity) net.sf.json.JSONObject.toBean(jsonObject1, WarningInfoEntity.class);

JSONString字节数组 转实体类

WarningInfoEntity warningInfoEntity = JSONObject.parseObject(new String(byte1,"utf-8"),WarningInfoEntity.class);

将实体类转换Stirng

WarningInfoEntity warningInfoEntity = new WarningInfoEntity()
String string = JSONObject.toJSONString(warningInfoEntity);

Object对象转换JSONObject对象, JSONObject对象转换实体类

Object object= condition.get("collectInfo");
JSONObject jsonObject = JSONObject.fromObject(object);
HospCollectInfoEntity infoEntity = (HospCollectInfoEntity) JSONObject.toBean(jsonObject, HospCollectInfoEntity.class);

map转JSONObject(map转String)

Map map = robotInfoService.selectOneById(result.toString());
String toJSONString = JSONObject.toJSONString(map);

从map里面get获取对像后直接强转list实体类强转list实体类前提是存进去的就是list实体类(先向下转,再向上转)

List<HospWasteCodeEntity> wasteCodeList = new ArrayList<>();
for (int i = 0; i<10;i++) {
   HospWasteCodeEntity wasteCode = new HospWasteCodeEntity();
   wasteCode.setTxm("txm +" + i);
   wasteCode.setFwtm("feiWuTiaoMa +" + i);
   wasteCode.setYyid(String.valueOf(yyid));
   wasteCode.setSj(new Date());
   wasteCodeList.add(wasteCode);
}

//先存进去list实体类
Map<String,Object> map = new HashMap<>();
map.put("wasteCodeList",wasteCodeList);
//强转list实体类前提是存进去的就是list实体类(先向下转,再向上转)
Map<String,Object> condition= new HashMap<>();
List<HospWasteCodeEntity> hospWasteCodeEntityList = (List<HospWasteCodeEntity>) condition.get("wasteCodeList");

jsonStirng转JSON数组

String jsonStirng = request.getParameter("condition");
JSONArray json = JSONArray.parseArray(jsonStirng);

map案例

HashMap<String,String>map = new HashMap<>();
    map.put("a","1");
    map.put("b","2");
    map.put("c","3");

//map转String
String stringJson = JSON.toJSONString(map);
//String转json
JSONObject jsonObject = JSON.parseObject(string);
//json转map
Map<String, String> jsonMap = JSONObject.toJavaObject(jsonObject, Map.class);
//String转map
Map<String, String> jsonMap1 = JSONObject.parseObject(json, Map.class);

Object 转对应 List<实体类> 通过谷歌装换工具进行转换

// 将json文本转化成json数组,再将json数组转化为具体类的线性集合

//import com.google.gson.reflect.TypeToken;

public static List<?> jsonTStringToJsonArrayToList(Object object) {

    List<?> list = new Gson().fromJson(new Gson().toJson(object), new TypeToken<List<HospBoxActEntity>>(){}.getType());

    return list;

}

实体类 转 Map集合 的方法 beanToMap

public static Map<String, Object> beanToMap(Object obj) {
        try {
            if (obj == null) {
                return new HashMap<String, Object>();
            }
            Map<String, Object> params = new HashMap<String, Object>(0);

            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!"class".equals(name)) {
                    Object value = propertyUtilsBean.getNestedProperty(obj, name);
                    if (name.length() > 1 && Character.isUpperCase(name.charAt(1))) {
                        // 如果第一个字母大于1,则将其小写处理,符合规范
                        char[] ac = name.toCharArray();
                        ac[0] = Character.toLowerCase(ac[0]);
                        name = new String(ac);
                    }
                    params.put(name, value);
                }
            }
            return params;
        } catch (Exception e) {
            logger.error("[数据类型转换失败]", e);
            throw new BeanConvertException("数据类型转换失败", e);
        }
    }

Map集合转 实体类 的方法 beanToMap

//将 MAP 转为 JAVABEAN 类型。
    public static <T> T mapToBean(Map<String, Object> map, Class<T> type) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
            T obj = type.newInstance(); // 创建 JavaBean 对象
            // 给 JavaBean 对象的属性赋值
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if (map.containsKey(propertyName)) {
                    // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
                    Object value = map.get(propertyName);
                    Object[] args = new Object[1];
                    args[0] = value;
                    if (descriptor.getWriteMethod() != null) {
                        descriptor.getWriteMethod().invoke(obj, args);
                    }
                }
            }
            return obj;
        } catch (Exception e) {
            logger.error("数据类型转换失败,error:{}", e);
            throw new BeanConvertException("数据类型转换失败", e);
        }
    }

Guess you like

Origin blog.csdn.net/qq_36961226/article/details/109095938