package com.bbzn.device.client.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
/**
* @Author wulongbo
* @Date 2020/7/6 15:43
* @Version 1.0
*/
public class JsonUtils {private static final Logger log = LoggerFactory.getLogger(JsonUtils.class);
/**
* byte 数组转换成 Json
*
* @param array
* @return JSONObject
*/
public static JSONObject byteToJson(byte[] array) {String body = JSONArray.toJSONString(array); // 先转换成 Json String
byte[] json = JSONObject.parseObject(body, byte[].class);// 转 json byte
String convent = new String(json); // byte 数组转换成 String
JSONObject jsonObject = JSONObject.parseObject(convent);
return jsonObject;
}
/**
* byte 数组转换成 Java bean
*
* @param array
* @return JSONObject
*/
public static <T> T byteToJaveBean(byte[] array, Class<T> clazz) throws InstantiationException, IllegalAccessException {JSONObject jsonObject = byteToJson(array);
T obj = clazz.newInstance();
return jsonObject.toJavaObject((Type) obj.getClass());
}
/**
* String 转换成 Json
*
* @param key
* @return JSONObject
*/
public static JSONObject stringToJson(String key) {return JSONObject.parseObject(key);
}
/**
* Java 对象转换成 String
*
* @return
*/
public static String objectToString(Object object) {return JSONArray.toJSONString(object);
}
/**
* Java bean 转换成 JSONObject
*
* @return
*/
public static JSONObject beanToJSONObject(Object object) {return JSONObject.parseObject(JSONObject.toJSON(object).toString());
}
/**
* 将 map 转换成 byte[]
*
* @return
*/
public static byte[] changeMapToByte(Map<String, Object> map) {byte[] bytes = null;
try {bytes = serilizableForMap(map).getBytes();} catch (Exception e) {log.error("map 到 byte[] 转换异样", e);
}
return bytes;
}
/**
* 将 byte[] 转换成 map
*
* @return
*/
public static Map<String, String> changeByteToMap(byte[] bytes) {
Map<String, String> retmap = null;
try {if (bytes != null) {retmap = deserilizableForMapFromFile(new String(bytes), String.class);
} else {log.error("changeByteToMap 中 bytes 为 null");
}
} catch (Exception e) {log.error("byte 到 map 转换异样", e);
}
return retmap;
}
/* 将 HashMap 序列化为字符串存入 json 文件中 */
public static String serilizableForMap(Object objMap)
throws IOException {String listString = JSON.toJSONString(objMap, true);// (maps,CityEntity.class);
return listString;
}
/* 将 json 文件中的内容读取进去,反序列化为 HashMap */
public static <T, K> HashMap<K, T> deserilizableForMapFromFile(String listString2, Class<T> clazz) throws IOException {Map<K, T> map = JSON.parseObject(listString2, new TypeReference<Map<K, T>>() {});
return (HashMap<K, T>) map;
}
}