博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java json
阅读量:6194 次
发布时间:2019-06-21

本文共 6200 字,大约阅读时间需要 20 分钟。

hot3.png

import java.io.IOException;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.commons.lang.StringUtils;import org.codehaus.jackson.JsonParseException;import org.codehaus.jackson.map.JsonMappingException;import org.codehaus.jackson.map.ObjectMapper;import org.codehaus.jackson.type.TypeReference;public class DataConverter {	/**	 * map 转变成bean	 * @param t	 * @param map	 * @return	 */	@SuppressWarnings({ "unchecked", "rawtypes" })	public static 
T map2Bean(T t,Map map) { T entity=null; try { Class clazz = t.getClass(); entity = (T)clazz.newInstance(); Set
keys = map.keySet(); for(String key:keys){ String fieldName = key; if(key.equals(key.toUpperCase())){ Field[] fields = clazz.getDeclaredFields(); for(Field field: fields){ if(field.getName().toUpperCase().equals(key)) fieldName=field.getName(); break; } } try { Class
paramClass = clazz.getDeclaredField(fieldName).getType(); String methodName = "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1); Method method = clazz.getMethod(methodName, paramClass); method.invoke(entity, map.get(key)); } catch (Exception e) { } } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } return entity; } /** * json转map * @param jsonStr * @return */ public static Map
jsonToMap(String jsonStr){ if(StringUtils.isBlank(jsonStr)){ return null; } ObjectMapper mapper = null; try { mapper = new ObjectMapper(); return mapper.readValue(jsonStr,new TypeReference
>(){}); } catch (JsonParseException e) { } catch (JsonMappingException e) { } catch (IOException e) { }finally{ mapper = null; } return null; } /** * map转变为json * @param obj * @return */ public static
String mapToJson(T obj){ String json = null; if (null == obj) { return json; } ObjectMapper mapper = null; try { mapper = new ObjectMapper(); json = mapper.writeValueAsString(obj); } catch (Exception e) { } finally { mapper = null; } return json; } /** * 将json转化为实体POJO * @param jsonStr * @param obj * @return */ public static
Object json2Obj(Class
clazz,String jsonStr) { T t = null; try { ObjectMapper objectMapper = new ObjectMapper(); t = (T) objectMapper.readValue(jsonStr,clazz); } catch (Exception e) { e.printStackTrace(); } return t; } /** * 将实体POJO(包括集合)转化为JSON * @param obj * @return */ public static
String object2Json(T obj) { ObjectMapper mapper = new ObjectMapper(); String jsonStr = ""; try { jsonStr = mapper.writeValueAsString(obj); } catch (IOException e) { } return jsonStr; } /** * json字符串转变为list集合 * @param clazz * @param json * @return */ @SuppressWarnings("unchecked") public static
List
json2List(Class
clazz,String json){ if(json == null){ return null; } net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(json); List
list = (List
) net.sf.json.JSONArray.toCollection(jsonArray,clazz); return list; } }
import java.io.IOException;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.List;import org.codehaus.jackson.JsonParseException;import org.codehaus.jackson.map.DeserializationConfig;import org.codehaus.jackson.map.JsonMappingException;import org.codehaus.jackson.map.ObjectMapper;import org.codehaus.jackson.map.ser.FilterProvider;import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;import org.codehaus.jackson.type.TypeReference;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.StringUtils;public class JsonUtil {	private static Logger logger = LoggerFactory.getLogger(JsonUtil.class) ;	private static ObjectMapper mapper = new ObjectMapper(); //must reuse!!	static{//		java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//		mapper.getDeserializationConfig().withDateFormat(df);		mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);	}	public static String serializeToJson(Object obj, String... ignoreProperties) {//		mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);		FilterProvider filterProvider = new SimpleFilterProvider().addFilter(				"ignorePropertiesFilter",				SimpleBeanPropertyFilter.serializeAllExcept(ignoreProperties));		String json;		try {			json = mapper.writer(filterProvider).writeValueAsString(obj);		} catch (Exception e) {			throw new RuntimeException(e);		} 		return json;	}	public static 
T unserializeFromJson(String json, Class
clazz) { try { T object=null; if(StringUtils.hasText(json)){ object = mapper.readValue(json, clazz); } return object; } catch (Exception e) { logger.error("can not serialize:"+json); e.printStackTrace(); throw new RuntimeException(e); } } public static
T unserializeFromJson(String json, Type type) { try { T object=null; if(StringUtils.hasText(json)){ object = mapper.readValue(json, mapper.getTypeFactory().constructType(type)); } return object; } catch (Exception e) { logger.error("can not serialize:"+json); e.printStackTrace(); throw new RuntimeException(e); } } public static
List
unserializeFromJsonAsList(String json, Class
cls) { try { List
object = mapper.readValue(json, mapper.getTypeFactory() .constructCollectionType(ArrayList.class, cls)); return object; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public static
T unserializeFromJsonByTypeReference(String json, TypeReference
typeReference) throws JsonParseException, JsonMappingException, IOException { T object = mapper.readValue(json, typeReference); return object; } public static
T convertValue(Object fromValue, Class
toValueType){ return mapper.convertValue(fromValue, toValueType); }}

转载于:https://my.oschina.net/v512345/blog/1509934

你可能感兴趣的文章
Merge Sort(Java)
查看>>
zookeeper选举原理
查看>>
XML
查看>>
基数排序
查看>>
[C++]利用栈实现字符串里的括号匹配
查看>>
JAVA线程控制
查看>>
数据标准化_1
查看>>
第十一周作业
查看>>
那些性感的让人尖叫的程序员
查看>>
验证码识别技术 Captcha Decode Technology
查看>>
洛谷 P2290 [HNOI2004]树的计数(bzoj[1211])
查看>>
IE和W3C兼容的时间切换器
查看>>
CentOS的MySQL报错:Can't connect to MySQL server
查看>>
Object.prototype.toString.call() , toString ,typof的返回值
查看>>
学习php值得关注的人和博客
查看>>
VS2013秘钥
查看>>
zabbix 介绍
查看>>
初识javascript
查看>>
AVR之bootloader介绍
查看>>
9-3NOIP模拟赛总结
查看>>