JsonUtil.java 1.66 KB
package cn.bxe.updatevideo.util;

import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;

/**
 * json工具类
 * @author yonson
 */
public class JsonUtil {
	
	/**
	 * 对像转化为json字符串
	 * @param obj
	 * @return
	 */
	public static String tranObjectToJsonStr(Object obj){
		
		return JSONObject.toJSONString(obj);
		
	}
	
	/**
	 * json字符串转化为对像
	 * @param jsonStr
	 * @return 
	 * @return
	 */
	public static <T extends Object> T tranJsonStrToObject(String jsonStr,Class<T> clazz){
		
		return (T)JSONObject.parseObject(jsonStr,clazz);
		
	}
	
	/**
	 * json字符串转化为列表
	 * @param jsonStr
	 * @param clazz
	 * @return
	 */
	public static <T extends Object> List<T> tranJsonStrToArray(String jsonStr,Class<T> clazz){
		
		return JSONObject.parseArray(jsonStr, clazz);
		
	}
	
	public static JSONObject tranJsonStrToJSONObject(String jsonStr){
		return JSONObject.parseObject(jsonStr);
	}


	public static Map tranJsonToMap(String jsonStr){
		try {
			Map mapObj = JSONObject.parseObject(jsonStr, Map.class);
			//for (Object map: mapObj.entrySet()){
			//	System.out.println(((Map.Entry)map).getKey()+"  "+((Map.Entry)map).getValue());
			//}
			return mapObj;
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 *
	 * @param jsonStr
	 * @param keyField
	 * @return
	 */
	public static String tranJsonToMapAndGetKValue(String jsonStr,String keyField){
		try {
			Map mapObj = tranJsonToMap(jsonStr);
			if(mapObj!=null && mapObj.containsKey(keyField)) {
				return String.valueOf(mapObj.get(keyField));
			}
			else
				return "";
		}catch (Exception e){
			e.printStackTrace();
		}
		return "";
	}

}