json⇌object,json⇌map,map⇌object以
2018-11-27 本文已影响26人
墨色尘埃
1、json转map
public class JsonToMapTest01 {
public static void main(String[] args){
String str = "{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}";
//第一种方式
Map maps = (Map)JSON.parse(str);
System.out.println("这个是用JSON类来解析JSON字符串!!!");
for (Object map : maps.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" " + ((Map.Entry)map).getValue());
}
//第二种方式
Map mapTypes = JSON.parseObject(str);
System.out.println("这个是用JSON类的parseObject来解析JSON字符串!!!");
for (Object obj : mapTypes.keySet()){
System.out.println("key为:"+obj+"值为:"+mapTypes.get(obj));
}
//第三种方式
Map mapType = JSON.parseObject(str,Map.class);
System.out.println("这个是用JSON类,指定解析类型,来解析JSON字符串!!!");
for (Object obj : mapType.keySet()){
System.out.println("key为:"+obj+"值为:"+mapType.get(obj));
}
//第四种方式
/**
* JSONObject是Map接口的一个实现类
*/
Map json = (Map) JSONObject.parse(str);
System.out.println("这个是用JSONObject类的parse方法来解析JSON字符串!!!");
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
//第五种方式
/**
* JSONObject是Map接口的一个实现类
*/
JSONObject jsonObject = JSONObject.parseObject(str);
System.out.println("这个是用JSONObject的parseObject方法来解析JSON字符串!!!");
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
//第六种方式
/**
* JSONObject是Map接口的一个实现类
*/
Map mapObj = JSONObject.parseObject(str,Map.class);
System.out.println("这个是用JSONObject的parseObject方法并执行返回类型来解析JSON字符串!!!");
for (Object map: json.entrySet()){
System.out.println(((Map.Entry)map).getKey()+" "+((Map.Entry)map).getValue());
}
String strArr = "{{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}," +
"{\"00\":\"zhangsan\",\"11\":\"lisi\",\"22\":\"wangwu\",\"33\":\"maliu\"}}";
// JSONArray.parse()
System.out.println(json);
}
}
2、map转json
Json字符串与Object对象相互转换的几种方式
① Json-Lib适用于JDK1.5,当使用高版本jdk时可能会报错,不建议使用。
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
--------------------------------
Map map = new HashMap();
map.put("msg", "yes");//map里面装有yes
JSONObject jsonObject = JSONObject.fromObject(map);
System.out.println("输出的结果是:" + jsonObject);
//3、将json对象转化为json字符串
String result = jsonObject.toString();
System.out.println(result);
② gson
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
--------------------------------
Gson gson = new Gson();
gson .toJson(param);
③ jackson
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
------------------------------------------------------------
@Autowired
ObjectMapper objectMapper;
Map<String, String> requestObj = new HashMap<>();
requestObj.put("invoiceCode", invoiceCode);
requestObj.put("invoiceNumber", invoiceNumber);
requestObj.put("billTime", billTime);
requestObj.put("checkCode", checkCode);
requestObj.put("invoiceAmount", invoiceAmount);
requestObj.put("token", getToken());
String requestStr = objectMapper.writeValueAsString(requestObj);
④ fastjson
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
--------------------------------
Map<String, Integer> params = new HashMap<String, Integer>();
params.put("invateId", 1);
params.put("applySourceId", 1);
Object o = JSONObject.toJSON(params);
System.out.println(o.toString());
//或者String json = JSON.toJSONString(param);
3/4、json转Object和Object转json
① Json-Lib
import net.sf.json.JSONObject;
public class JsonLibDemo {
public static void main(String[] args) {
//创建测试object
User user = new User("李宁",24,"北京");
System.out.println(user);
//Object转成json字符串
JSONObject jsonObject = JSONObject.fromObject(user);
String json = jsonObject.toString();
System.out.println(json);
//json字符串转成Object
JSONObject jsonObject1 = JSONObject.fromObject(json);
User user1 = (User) JSONObject.toBean(jsonObject1,User.class);
System.out.println(user1);
}
}
② org.json
maven依赖
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20170516</version>
</dependency>
--------------------------------
import org.json.JSONObject;
public class OrgJsonDemo {
public static void main(String[] args) {
//创建测试object
User user = new User("李宁",24,"北京");
System.out.println(user);
//Object转成json字符串
String json = new JSONObject(user).toString();
System.out.println(json);
//json字符串转成Object
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
Integer age = jsonObject.getInt("age");
String location = jsonObject.getString("location");
User user1 = new User(name,age,location);
System.out.println(user1);
}
}
③ Jackson
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
public static void main(String[] args) {
//创建测试object
User user = new User("李宁",24,"北京");
System.out.println(user);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
//Object转成json字符串
String json = mapper.writeValueAsString(user);
System.out.println(json);
//json字符串转成Object
User user1 = mapper.readValue(json,User.class);
System.out.println(user1);
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
④ Gson
import com.google.gson.Gson;
public class GsonDemo {
public static void main(String[] args) {
//创建测试object
User user = new User("李宁",24,"北京");
System.out.println(user);
//转成json字符串
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
//json字符串转成对象
User user1 = gson.fromJson(json,User.class);
System.out.println(user1);
}
}
⑤ FastJson
import com.alibaba.fastjson.JSON;
public class FastJsonDemo {
public static void main(String[] args) {
//创建测试object
User user = new User("李宁",24,"北京");
System.out.println(user);
//转成json字符串
String json = JSON.toJSON(user).toString();
System.out.println(json);
//json字符串转成对象
User user1 = JSON.parseObject(json,User.class);
System.out.println(user1);
}
}
json-lib时间有些久远,jar包只更新到2010年
org.json用起来有些繁琐
Jackson、Gson、FastJson只需一两句话就可以搞定
5/6、map转Object和Object转map
map和object互相转换
① 使用Introspector进行转换
/**
* 将Map对象通过反射机制转换成Bean对象
*/
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
setter.invoke(obj, map.get(property.getName()));
}
}
return obj;
}
/**
* 将Object装换为map
*/
public static Map<String, Object> objectToMap(Object obj) throws Exception {
if (obj == null)
return null;
Map<String, Object> map = new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
//默认PropertyDescriptor会有一个class对象,剔除之
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter != null ? getter.invoke(obj) : null;
map.put(key, value);
}
return map;
}
② 使用reflect进行转换:
方法一
/**
* 将Map对象通过反射机制转换成Bean对象
*/
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
/**
* 将Object装换为map
*/
public static Map<String, Object> objectToMap(Object obj) throws Exception {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
方法二
/**
* 将Map对象通过反射机制转换成Bean对象
*/
public static Object mapToBean(Map<String, Object> map, Class<?> clazz) throws Exception {
Object obj = clazz.newInstance();
if (map != null && map.size() > 0) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String propertyName = entry.getKey(); //属性名
Object value = entry.getValue();
String setMethodName = "set"
+ propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
Field field = getClassField(clazz, propertyName);
if (field == null)
continue;
Class<?> fieldTypeClass = field.getType();
value = convertValType(value, fieldTypeClass); //todo标记,见最后解释
try {
clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
return obj;
}
/**
* 将Object装换为map
*/
public static <T> Map<String, Object> beanToMap(T bean) {
Map<String, Object> map = new LinkedHashMap<>(); //按插入的顺序进行有序存储
Class<?> clazz = bean.getClass();
for (Field field : clazz.getSuperclass().getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
try {
value = field.get(bean);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
map.put(fieldName, value);
}
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
try {
value = field.get(bean);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
map.put(fieldName, value);
}
return map;
}
todo标记
map→Object过程中,因为类型不一致报错java.lang.IllegalArgumentException: argument type mismatch
完整MapBeanUtil类
package com.cicdi.servertemplate.common.util;
import org.springframework.beans.factory.annotation.Value;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by HASEE on 2018/10/19 16:34
*/
public class MapBeanUtil {
@Value("${pName}")
private String pName;
private static String modelName = "com.cicdi.servertemplate.modules.baselibrary.model.";
/**
* 将对象装换为map
*
* @param bean
* @return
*/
public static <T> Map<String, Object> beanToMap(T bean) {
Map<String, Object> map = new LinkedHashMap<>(); //按插入的顺序进行有序存储
Class<?> clazz = bean.getClass();
for (Field field : clazz.getSuperclass().getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
try {
value = field.get(bean);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
map.put(fieldName, value);
}
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
try {
value = field.get(bean);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
map.put(fieldName, value);
}
return map;
}
/**
* 将Map对象通过反射机制转换成Bean对象
*
* @param map 存放数据的map对象
* @param clazz 待转换的class
* @return 转换后的Bean对象
* @throws Exception 异常
*/
public static Object mapToBean(Map<String, Object> map, Class<?> clazz) throws Exception {
Object obj = clazz.newInstance();
if (map != null && map.size() > 0) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String propertyName = entry.getKey(); //属性名
Object value = entry.getValue();
String setMethodName = "set"
+ propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
Field field = getClassField(clazz, propertyName);
if (field == null)
continue;
Class<?> fieldTypeClass = field.getType();
value = convertValType(value, fieldTypeClass);
try {
clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
return obj;
}
/**
* 获取指定字段名称查找在class中的对应的Field对象(包括查找父类)
*
* @param clazz 指定的class
* @param fieldName 字段名称
* @return Field对象
*/
public static Field getClassField(Class<?> clazz, String fieldName) {
if (Object.class.getName().equals(clazz.getName())) {
return null;
}
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {// 简单的递归一下
return getClassField(superClass, fieldName);
}
return null;
}
/**
* 将Object类型的值,转换成bean对象属性里对应的类型值
*
* @param value Object对象值
* @param fieldTypeClass 属性的类型
* @return 转换后的值
*/
public static Object convertValType(Object value, Class<?> fieldTypeClass) {
Object retVal = null;
if (Long.class.getName().equals(fieldTypeClass.getName())
|| long.class.getName().equals(fieldTypeClass.getName())) {
retVal = Long.parseLong(value.toString());
} else if (Integer.class.getName().equals(fieldTypeClass.getName())
|| int.class.getName().equals(fieldTypeClass.getName())) {
retVal = Integer.parseInt(value.toString());
} else if (Float.class.getName().equals(fieldTypeClass.getName())
|| float.class.getName().equals(fieldTypeClass.getName())) {
retVal = Float.parseFloat(value.toString());
} else if (Double.class.getName().equals(fieldTypeClass.getName())
|| double.class.getName().equals(fieldTypeClass.getName())) {
retVal = Double.parseDouble(value.toString());
} else {
retVal = value;
}
return retVal;
}
/**
* 不同的输入map,返回不同Object
*
* @param tableName
* @param map
* @return
*/
public static Object returnObj(String tableName, Map map) {
Object obj = null;
Class<?> aClass = null;
try {
//利用反射,通过完整类名找到类对象
aClass = Class.forName(modelName + tableName).newInstance().getClass();
obj = MapBeanUtil.mapToBean(map, aClass);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 原表转换备份表
* OPERATION:操作标志0:插入,1:更新,2:删除
*/
public static Map transMap(Object obj, Object objBak, String operation) {
Map<String, Object> map1 = MapBeanUtil.beanToMap(obj); //主键id有值了
String id = (String) map1.entrySet().iterator().next().getValue(); //原表主键
Map<String, Object> map2 = MapBeanUtil.beanToMap(objBak); //备份表map结构,有顺序
int pos = 0;
for (Iterator<String> iterator = map2.keySet().iterator(); iterator.hasNext(); pos++) {
String keyId = iterator.next();
if (pos == 1) { //备份表中的外键,取map中的第二个元素
map2.put(keyId, id);
}
if (keyId.equals("isNew")) {
map2.put(keyId, "1");
} else if (keyId.equals("operation")) {
if (operation.equals("insert")) {
map2.put(keyId, "0");
} else if (operation.equals("update")) {
map2.put(keyId, "1");
} else if (operation.equals("delete")) {
map2.put(keyId, "2");
}
} else if (keyId.equals("batchTime")) {
map2.put(keyId, new Date());
}
}
return map2;
}
/**
*
*/
public static Object getValue(String type, String name, Object model) {
Object value = null;
try {
if (type.equals("class java.lang.String")) { // 如果type是类类型,则前面包含"class ",后面跟类名
Method m = model.getClass().getMethod("get" + name);
value = (String) m.invoke(model); // 调用getter方法获取属性值
if (value == null) {
m = model.getClass().getMethod("set" + name, String.class);
m.invoke(model, "");
}
}
if (type.equals("class java.lang.Integer")) {
Method m = model.getClass().getMethod("get" + name);
value = (Integer) m.invoke(model);
if (value == null) {
m = model.getClass().getMethod("set" + name, Integer.class);
m.invoke(model, 0);
}
}
if (type.equals("class java.lang.Boolean")) {
Method m = model.getClass().getMethod("get" + name);
value = (Boolean) m.invoke(model);
if (value == null) {
m = model.getClass().getMethod("set" + name, Boolean.class);
m.invoke(model, false);
}
}
if (type.equals("class java.util.Date")) {
Method m = model.getClass().getMethod("get" + name);
value = (Date) m.invoke(model);
if (value == null) {
m = model.getClass().getMethod("set" + name, Date.class);
m.invoke(model, new Date());
}
}
// 如果有需要,可以仿照上面继续进行扩充,再增加对其它类型的判断
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
/**
* 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。</br>
* 例如:HelloWorld->HELLO_WORLD
*
* @param name 转换前的驼峰式命名的字符串
* @return 转换后下划线大写方式命名的字符串
*/
public static String underscoreName(String name) {
StringBuilder result = new StringBuilder();
if (name != null && name.length() > 0) {
// 将第一个字符处理成大写
result.append(name.substring(0, 1).toUpperCase());
// 循环处理其余字符
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
// 在大写字母前添加下划线
if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
result.append("_");
}
// 其他字符直接转成大写
result.append(s.toUpperCase());
}
}
return result.toString();
}
}