jsonutil 学习使用

  1. packagecomm;
  2. importjava.text.SimpleDateFormat;
  3. importjava.util.ArrayList;
  4. importjava.util.Collection;
  5. importjava.util.Date;
  6. importjava.util.HashMap;
  7. importjava.util.Iterator;
  8. importjava.util.List;
  9. importjava.util.Map;
  10. importnet.sf.ezmorph.MorpherRegistry;
  11. importnet.sf.ezmorph.object.DateMorpher;
  12. importnet.sf.json.JSONArray;
  13. importnet.sf.json.JSONObject;
  14. importnet.sf.json.JsonConfig;
  15. importnet.sf.json.processors.JsonValueProcessor;
  16. importnet.sf.json.util.JSONUtils;
  17. importnet.sf.json.xml.XMLSerializer;
  18. publicclassJsonUtil{
  19. /**
  20. *设置日期转换格式
  21. */
  22. static{
  23. //注册器
  24. MorpherRegistrymr=JSONUtils.getMorpherRegistry();
  25. //可转换的日期格式,即Json串中可以出现以下格式的日期与时间
  26. DateMorpherdm=newDateMorpher(newString[]{Util.YYYY_MM_DD,
  27. Util.YYYY_MM_DD_HH_MM_ss,Util.HH_MM_ss,Util.YYYYMMDD,
  28. Util.YYYYMMDDHHMMSS,Util.HHMMss});
  29. mr.registerMorpher(dm);
  30. }
  31. /**
  32. *从json串转换成实体对象
  33. *@paramjsonObjStre.g.{'name':'get','dateAttr':'2009-11-12'}
  34. *@paramclazzPerson.class
  35. *@return
  36. */
  37. publicstaticObjectgetDtoFromJsonObjStr(StringjsonObjStr,Classclazz){
  38. returnJSONObject.toBean(JSONObject.fromObject(jsonObjStr),clazz);
  39. }
  40. /**
  41. *从json串转换成实体对象,并且实体集合属性存有另外实体Bean
  42. *@paramjsonObjStre.g.{'data':[{'name':'get'},{'name':'set'}]}
  43. *@paramclazze.g.MyBean.class
  44. *@paramclassMape.g.classMap.put("data",Person.class)
  45. *@returnObject
  46. */
  47. publicstaticObjectgetDtoFromJsonObjStr(StringjsonObjStr,Classclazz,MapclassMap){
  48. returnJSONObject.toBean(JSONObject.fromObject(jsonObjStr),clazz,classMap);
  49. }
  50. /**
  51. *把一个json数组串转换成普通数组
  52. *@paramjsonArrStre.g.['get',1,true,null]
  53. *@returnObject[]
  54. */
  55. publicstaticObject[]getArrFromJsonArrStr(StringjsonArrStr){
  56. returnJSONArray.fromObject(jsonArrStr).toArray();
  57. }
  58. /**
  59. *把一个json数组串转换成实体数组
  60. *@paramjsonArrStre.g.[{'name':'get'},{'name':'set'}]
  61. *@paramclazze.g.Person.class
  62. *@returnObject[]
  63. */
  64. publicstaticObject[]getDtoArrFromJsonArrStr(StringjsonArrStr,Classclazz){
  65. JSONArrayjsonArr=JSONArray.fromObject(jsonArrStr);
  66. Object[]objArr=newObject[jsonArr.size()];
  67. for(inti=0;i<jsonArr.size();i++){
  68. objArr[i]=JSONObject.toBean(jsonArr.getJSONObject(i),clazz);
  69. }
  70. returnobjArr;
  71. }
  72. /**
  73. *把一个json数组串转换成实体数组,且数组元素的属性含有另外实例Bean
  74. *@paramjsonArrStre.g.[{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]
  75. *@paramclazze.g.MyBean.class
  76. *@paramclassMape.g.classMap.put("data",Person.class)
  77. *@returnObject[]
  78. */
  79. publicstaticObject[]getDtoArrFromJsonArrStr(StringjsonArrStr,Classclazz,
  80. MapclassMap){
  81. JSONArrayarray=JSONArray.fromObject(jsonArrStr);
  82. Object[]obj=newObject[array.size()];
  83. for(inti=0;i<array.size();i++){
  84. JSONObjectjsonObject=array.getJSONObject(i);
  85. obj[i]=JSONObject.toBean(jsonObject,clazz,classMap);
  86. }
  87. returnobj;
  88. }
  89. /**
  90. *把一个json数组串转换成存放普通类型元素的集合
  91. *@paramjsonArrStre.g.['get',1,true,null]
  92. *@returnList
  93. */
  94. publicstaticListgetListFromJsonArrStr(StringjsonArrStr){
  95. JSONArrayjsonArr=JSONArray.fromObject(jsonArrStr);
  96. Listlist=newArrayList();
  97. for(inti=0;i<jsonArr.size();i++){
  98. list.add(jsonArr.get(i));
  99. }
  100. returnlist;
  101. }
  102. /**
  103. *把一个json数组串转换成集合,且集合里存放的为实例Bean
  104. *@paramjsonArrStre.g.[{'name':'get'},{'name':'set'}]
  105. *@paramclazz
  106. *@returnList
  107. */
  108. publicstaticListgetListFromJsonArrStr(StringjsonArrStr,Classclazz){
  109. JSONArrayjsonArr=JSONArray.fromObject(jsonArrStr);
  110. Listlist=newArrayList();
  111. for(inti=0;i<jsonArr.size();i++){
  112. list.add(JSONObject.toBean(jsonArr.getJSONObject(i),clazz));
  113. }
  114. returnlist;
  115. }
  116. /**
  117. *把一个json数组串转换成集合,且集合里的对象的属性含有另外实例Bean
  118. *@paramjsonArrStre.g.[{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]
  119. *@paramclazze.g.MyBean.class
  120. *@paramclassMape.g.classMap.put("data",Person.class)
  121. *@returnList
  122. */
  123. publicstaticListgetListFromJsonArrStr(StringjsonArrStr,Classclazz,MapclassMap){
  124. JSONArrayjsonArr=JSONArray.fromObject(jsonArrStr);
  125. Listlist=newArrayList();
  126. for(inti=0;i<jsonArr.size();i++){
  127. list.add(JSONObject.toBean(jsonArr.getJSONObject(i),clazz,classMap));
  128. }
  129. returnlist;
  130. }
  131. /**
  132. *把json对象串转换成map对象
  133. *@paramjsonObjStre.g.{'name':'get','int':1,'double',1.1,'null':null}
  134. *@returnMap
  135. */
  136. publicstaticMapgetMapFromJsonObjStr(StringjsonObjStr){
  137. JSONObjectjsonObject=JSONObject.fromObject(jsonObjStr);
  138. Mapmap=newHashMap();
  139. for(Iteratoriter=jsonObject.keys();iter.hasNext();){
  140. Stringkey=(String)iter.next();
  141. map.put(key,jsonObject.get(key));
  142. }
  143. returnmap;
  144. }
  145. /**
  146. *把json对象串转换成map对象,且map对象里存放的为其他实体Bean
  147. *@paramjsonObjStre.g.{'data1':{'name':'get'},'data2':{'name':'set'}}
  148. *@paramclazze.g.Person.class
  149. *@returnMap
  150. */
  151. publicstaticMapgetMapFromJsonObjStr(StringjsonObjStr,Classclazz){
  152. JSONObjectjsonObject=JSONObject.fromObject(jsonObjStr);
  153. Mapmap=newHashMap();
  154. for(Iteratoriter=jsonObject.keys();iter.hasNext();){
  155. Stringkey=(String)iter.next();
  156. map.put(key,JSONObject.toBean(jsonObject.getJSONObject(key),clazz));
  157. }
  158. returnmap;
  159. }
  160. /**
  161. *把json对象串转换成map对象,且map对象里存放的其他实体Bean还含有另外实体Bean
  162. *@paramjsonObjStre.g.{'mybean':{'data':[{'name':'get'}]}}
  163. *@paramclazze.g.MyBean.class
  164. *@paramclassMape.g.classMap.put("data",Person.class)
  165. *@returnMap
  166. */
  167. publicstaticMapgetMapFromJsonObjStr(StringjsonObjStr,Classclazz,MapclassMap){
  168. JSONObjectjsonObject=JSONObject.fromObject(jsonObjStr);
  169. Mapmap=newHashMap();
  170. for(Iteratoriter=jsonObject.keys();iter.hasNext();){
  171. Stringkey=(String)iter.next();
  172. map.put(key,JSONObject
  173. .toBean(jsonObject.getJSONObject(key),clazz,classMap));
  174. }
  175. returnmap;
  176. }
  177. /**
  178. *把实体Bean、Map对象、数组、列表集合转换成Json串
  179. *@paramobj
  180. *@return
  181. *@throwsExceptionString
  182. */
  183. publicstaticStringgetJsonStr(Objectobj){
  184. StringjsonStr=null;
  185. //Json配置
  186. JsonConfigjsonCfg=newJsonConfig();
  187. //注册日期处理器
  188. jsonCfg.registerJsonValueProcessor(java.util.Date.class,
  189. newJsonDateValueProcessor(Util.YYYY_MM_DD_HH_MM_ss));
  190. if(obj==null){
  191. return"{}";
  192. }
  193. if(objinstanceofCollection||objinstanceofObject[]){
  194. jsonStr=JSONArray.fromObject(obj,jsonCfg).toString();
  195. }else{
  196. jsonStr=JSONObject.fromObject(obj,jsonCfg).toString();
  197. }
  198. returnjsonStr;
  199. }
  200. /**
  201. *把json串、数组、集合(collectionmap)、实体Bean转换成XML
  202. *XMLSerializerAPI:
  203. *http://json-lib.sourceforge.net/apidocs/net/sf/json/xml/XMLSerializer.html
  204. *具体实例请参考:
  205. *http://json-lib.sourceforge.net/xref-test/net/sf/json/xml/TestXMLSerializer_writes.html
  206. *http://json-lib.sourceforge.net/xref-test/net/sf/json/xml/TestXMLSerializer_writes.html
  207. *@paramobj
  208. *@return
  209. *@throwsExceptionString
  210. */
  211. publicstaticStringgetXMLFromObj(Objectobj){
  212. XMLSerializerxmlSerial=newXMLSerializer();
  213. //Json配置
  214. JsonConfigjsonCfg=newJsonConfig();
  215. //注册日期处理器
  216. jsonCfg.registerJsonValueProcessor(java.util.Date.class,
  217. newJsonDateValueProcessor(Util.YYYY_MM_DD_HH_MM_ss));
  218. if((String.class.isInstance(obj)&&String.valueOf(obj).startsWith("["))
  219. ||obj.getClass().isArray()||Collection.class.isInstance(obj)){
  220. JSONArrayjsonArr=JSONArray.fromObject(obj,jsonCfg);
  221. returnxmlSerial.write(jsonArr);
  222. }else{
  223. JSONObjectjsonObj=JSONObject.fromObject(obj,jsonCfg);
  224. returnxmlSerial.write(jsonObj);
  225. }
  226. }
  227. /**
  228. *从XML转json串
  229. *@paramxml
  230. *@returnString
  231. */
  232. publicstaticStringgetJsonStrFromXML(Stringxml){
  233. XMLSerializerxmlSerial=newXMLSerializer();
  234. returnString.valueOf(xmlSerial.read(xml));
  235. }
  236. }
  237. /**
  238. *json日期值处理器实现
  239. *(C)2009-9-11,jzj
  240. */
  241. classJsonDateValueProcessorimplementsJsonValueProcessor{
  242. privateStringformat=Util.YYYY_MM_DD_HH_MM_ss;
  243. publicJsonDateValueProcessor(){
  244. }
  245. publicJsonDateValueProcessor(Stringformat){
  246. this.format=format;
  247. }
  248. publicObjectprocessArrayValue(Objectvalue,JsonConfigjsonConfig){
  249. returnprocess(value,jsonConfig);
  250. }
  251. publicObjectprocessObjectValue(Stringkey,Objectvalue,JsonConfigjsonConfig){
  252. returnprocess(value,jsonConfig);
  253. }
  254. privateObjectprocess(Objectvalue,JsonConfigjsonConfig){
  255. if(valueinstanceofDate){
  256. Stringstr=newSimpleDateFormat(format).format((Date)value);
  257. returnstr;
  258. }
  259. returnvalue==null?null:value.toString();
  260. }
  261. publicStringgetFormat(){
  262. returnformat;
  263. }
  264. publicvoidsetFormat(Stringformat){
  265. this.format=format;
  266. }
  267. }
package comm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.ezmorph.MorpherRegistry;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.JSONUtils;
import net.sf.json.xml.XMLSerializer;

public class JsonUtil {

	/**
	 * 设置日期转换格式
	 */
	static {
		//注册器
		MorpherRegistry mr = JSONUtils.getMorpherRegistry();

		//可转换的日期格式,即Json串中可以出现以下格式的日期与时间
		DateMorpher dm = new DateMorpher(new String[] { Util.YYYY_MM_DD,
				Util.YYYY_MM_DD_HH_MM_ss, Util.HH_MM_ss, Util.YYYYMMDD,
				Util.YYYYMMDDHHMMSS, Util.HHMMss });
		mr.registerMorpher(dm);
	}

	/**
	* 从json串转换成实体对象
	* @param jsonObjStr e.g. {'name':'get','dateAttr':'2009-11-12'}
	* @param clazz Person.class
	* @return
	*/
	public static Object getDtoFromJsonObjStr(String jsonObjStr, Class clazz) {
		return JSONObject.toBean(JSONObject.fromObject(jsonObjStr), clazz);
	}

	/**
	* 从json串转换成实体对象,并且实体集合属性存有另外实体Bean
	* @param jsonObjStr e.g. {'data':[{'name':'get'},{'name':'set'}]}
	* @param clazz e.g. MyBean.class
	* @param classMap e.g. classMap.put("data", Person.class)
	* @return Object
	*/
	public static Object getDtoFromJsonObjStr(String jsonObjStr, Class clazz, Map classMap) {
		return JSONObject.toBean(JSONObject.fromObject(jsonObjStr), clazz, classMap);
	}

	/**
	* 把一个json数组串转换成普通数组
	* @param jsonArrStr  e.g. ['get',1,true,null]
	* @return Object[]
	*/
	public static Object[] getArrFromJsonArrStr(String jsonArrStr) {
		return JSONArray.fromObject(jsonArrStr).toArray();
	}

	/**
	* 把一个json数组串转换成实体数组
	* @param jsonArrStr e.g. [{'name':'get'},{'name':'set'}]
	* @param clazz e.g. Person.class
	* @return Object[]
	*/
	public static Object[] getDtoArrFromJsonArrStr(String jsonArrStr, Class clazz) {
		JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
		Object[] objArr = new Object[jsonArr.size()];
		for (int i = 0; i < jsonArr.size(); i++) {
			objArr[i] = JSONObject.toBean(jsonArr.getJSONObject(i), clazz);
		}
		return objArr;
	}

	/**
	* 把一个json数组串转换成实体数组,且数组元素的属性含有另外实例Bean
	* @param jsonArrStr e.g. [{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]
	* @param clazz e.g. MyBean.class
	* @param classMap e.g. classMap.put("data", Person.class)
	* @return Object[]
	*/
	public static Object[] getDtoArrFromJsonArrStr(String jsonArrStr, Class clazz,
			Map classMap) {
		JSONArray array = JSONArray.fromObject(jsonArrStr);
		Object[] obj = new Object[array.size()];
		for (int i = 0; i < array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			obj[i] = JSONObject.toBean(jsonObject, clazz, classMap);
		}
		return obj;
	}

	/**
	* 把一个json数组串转换成存放普通类型元素的集合
	* @param jsonArrStr  e.g. ['get',1,true,null]
	* @return List
	*/
	public static List getListFromJsonArrStr(String jsonArrStr) {
		JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
		List list = new ArrayList();
		for (int i = 0; i < jsonArr.size(); i++) {
			list.add(jsonArr.get(i));
		}
		return list;
	}

	/**
	* 把一个json数组串转换成集合,且集合里存放的为实例Bean
	* @param jsonArrStr e.g. [{'name':'get'},{'name':'set'}]
	* @param clazz
	* @return List
	*/
	public static List getListFromJsonArrStr(String jsonArrStr, Class clazz) {
		JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
		List list = new ArrayList();
		for (int i = 0; i < jsonArr.size(); i++) {
			list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz));
		}
		return list;
	}

	/**
	* 把一个json数组串转换成集合,且集合里的对象的属性含有另外实例Bean
	* @param jsonArrStr e.g. [{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]
	* @param clazz e.g. MyBean.class
	* @param classMap e.g. classMap.put("data", Person.class)
	* @return List
	*/
	public static List getListFromJsonArrStr(String jsonArrStr, Class clazz, Map classMap) {
		JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
		List list = new ArrayList();
		for (int i = 0; i < jsonArr.size(); i++) {
			list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz, classMap));
		}
		return list;
	}

	/**
	* 把json对象串转换成map对象
	* @param jsonObjStr e.g. {'name':'get','int':1,'double',1.1,'null':null}
	* @return Map
	*/
	public static Map getMapFromJsonObjStr(String jsonObjStr) {
		JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);

		Map map = new HashMap();
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			map.put(key, jsonObject.get(key));
		}
		return map;
	}

	/**
	* 把json对象串转换成map对象,且map对象里存放的为其他实体Bean
	* @param jsonObjStr e.g. {'data1':{'name':'get'},'data2':{'name':'set'}}
	* @param clazz e.g. Person.class
	* @return Map
	*/
	public static Map getMapFromJsonObjStr(String jsonObjStr, Class clazz) {
		JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);

		Map map = new HashMap();
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			map.put(key, JSONObject.toBean(jsonObject.getJSONObject(key), clazz));
		}
		return map;
	}

	/**
	 * 把json对象串转换成map对象,且map对象里存放的其他实体Bean还含有另外实体Bean
	 * @param jsonObjStr e.g. {'mybean':{'data':[{'name':'get'}]}}
	 * @param clazz e.g. MyBean.class
	 * @param classMap	e.g. classMap.put("data", Person.class)
	 * @return Map
	 */
	public static Map getMapFromJsonObjStr(String jsonObjStr, Class clazz, Map classMap) {
		JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);

		Map map = new HashMap();
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			map.put(key, JSONObject
					.toBean(jsonObject.getJSONObject(key), clazz, classMap));
		}
		return map;
	}

	/**
	 * 把实体Bean、Map对象、数组、列表集合转换成Json串
	 * @param obj 
	 * @return
	 * @throws Exception String
	 */
	public static String getJsonStr(Object obj) {
		String jsonStr = null;
		//Json配置    
		JsonConfig jsonCfg = new JsonConfig();

		//注册日期处理器
		jsonCfg.registerJsonValueProcessor(java.util.Date.class,
				new JsonDateValueProcessor(Util.YYYY_MM_DD_HH_MM_ss));
		if (obj == null) {
			return "{}";
		}

		if (obj instanceof Collection || obj instanceof Object[]) {
			jsonStr = JSONArray.fromObject(obj, jsonCfg).toString();
		} else {
			jsonStr = JSONObject.fromObject(obj, jsonCfg).toString();
		}

		return jsonStr;
	}

	/**
	 * 把json串、数组、集合(collection map)、实体Bean转换成XML
	 * XMLSerializer API:
	 * http://json-lib.sourceforge.net/apidocs/net/sf/json/xml/XMLSerializer.html
	 * 具体实例请参考:
	 * http://json-lib.sourceforge.net/xref-test/net/sf/json/xml/TestXMLSerializer_writes.html
	 * http://json-lib.sourceforge.net/xref-test/net/sf/json/xml/TestXMLSerializer_writes.html
	 * @param obj 
	 * @return
	 * @throws Exception String
	 */
	public static String getXMLFromObj(Object obj) {
		XMLSerializer xmlSerial = new XMLSerializer();

		//Json配置    
		JsonConfig jsonCfg = new JsonConfig();

		//注册日期处理器
		jsonCfg.registerJsonValueProcessor(java.util.Date.class,
				new JsonDateValueProcessor(Util.YYYY_MM_DD_HH_MM_ss));

		if ((String.class.isInstance(obj) && String.valueOf(obj).startsWith("["))
				|| obj.getClass().isArray() || Collection.class.isInstance(obj)) {
			JSONArray jsonArr = JSONArray.fromObject(obj, jsonCfg);
			return xmlSerial.write(jsonArr);
		} else {
			JSONObject jsonObj = JSONObject.fromObject(obj, jsonCfg);
			return xmlSerial.write(jsonObj);
		}
	}

	/**
	 * 从XML转json串
	 * @param xml
	 * @return String
	 */
	public static String getJsonStrFromXML(String xml) {
		XMLSerializer xmlSerial = new XMLSerializer();
		return String.valueOf(xmlSerial.read(xml));
	}

}

/**
 * json日期值处理器实现  
 * (C) 2009-9-11, jzj
 */
class JsonDateValueProcessor implements JsonValueProcessor {

	private String format = Util.YYYY_MM_DD_HH_MM_ss;

	public JsonDateValueProcessor() {

	}

	public JsonDateValueProcessor(String format) {
		this.format = format;
	}

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value, jsonConfig);
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		return process(value, jsonConfig);
	}

	private Object process(Object value, JsonConfig jsonConfig) {
		if (value instanceof Date) {
			String str = new SimpleDateFormat(format).format((Date) value);
			return str;
		}
		return value == null ? null : value.toString();
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

}
  • JsonUtilTest

Java代码 复制代码 收藏代码
  1. packagecomm.test;
  2. importjava.text.SimpleDateFormat;
  3. importjava.util.ArrayList;
  4. importjava.util.Date;
  5. importjava.util.HashMap;
  6. importjava.util.Iterator;
  7. importjava.util.LinkedHashMap;
  8. importjava.util.LinkedHashSet;
  9. importjava.util.List;
  10. importjava.util.Map;
  11. importjava.util.Set;
  12. importjunit.framework.TestCase;
  13. importcomm.JsonUtil;
  14. /**
  15. *JsonUtil测试类
  16. *(C)2009-9-11,jzj
  17. */
  18. publicclassJsonUtilTestextendsTestCase{
  19. /**
  20. *从json串转换成实体对象,且实体中Date属性能正确转换
  21. *void
  22. */
  23. publicvoidtestGetDtoFromJsonObjStr1(){
  24. Stringjson="{'name':'get','dateAttr':'2009-11-12'}";
  25. Personps=(Person)JsonUtil.getDtoFromJsonObjStr(json,Person.class);
  26. //print:get
  27. System.out.println(ps.getName());
  28. SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");
  29. //print:2009-11-12
  30. System.out.println(sdf.format(ps.getDateAttr()));
  31. }
  32. /**
  33. *从json串转换成实体对象,并且实体集合属性存有另外实体Bean
  34. *void
  35. */
  36. publicvoidtestGetDtoFromJsonObjStr3(){
  37. Stringjson="{'data':[{'name':'get'},{'name':'set'}]}";
  38. MapclassMap=newHashMap();
  39. classMap.put("data",Person.class);
  40. MyBeanmyBean=(MyBean)JsonUtil.getDtoFromJsonObjStr(json,MyBean.class,
  41. classMap);
  42. //print:classcomm.test.Personname=get
  43. System.out.println(myBean.getData().get(0).getClass()+"name="
  44. +((Person)myBean.getData().get(0)).getName());
  45. //print:classcomm.test.Personname=set
  46. System.out.println(myBean.getData().get(1).getClass()+"name="
  47. +((Person)myBean.getData().get(1)).getName());
  48. }
  49. /**
  50. *把一个json数组串转换成普通数组
  51. *void
  52. */
  53. publicvoidtestGetArrFromJsonArrStr(){
  54. Stringjson="['get',1,true,null]";
  55. Object[]objArr=JsonUtil.getArrFromJsonArrStr(json);
  56. for(inti=0;i<objArr.length;i++){
  57. System.out.println(objArr[i].getClass()+""+objArr[i]);
  58. }
  59. /*print:
  60. classjava.lang.Stringget
  61. classjava.lang.Integer1
  62. classjava.lang.Booleantrue
  63. classnet.sf.json.JSONNullnull
  64. */
  65. }
  66. /**
  67. *把一个json数组串转换成实体数组
  68. *void
  69. */
  70. publicvoidtestGetDtoArrFromJsonArrStr1(){
  71. Stringjson="[{'name':'get'},{'name':'set'}]";
  72. Object[]objArr=JsonUtil.getDtoArrFromJsonArrStr(json,Person.class);
  73. for(inti=0;i<objArr.length;i++){
  74. System.out.println(objArr[i].getClass()+"name="
  75. +((Person)objArr[i]).getName());
  76. }
  77. /*print:
  78. classcomm.test.Personname=get
  79. classcomm.test.Personname=set
  80. */
  81. }
  82. /**
  83. *把一个json数组串转换成实体数组,且数组元素的属性含有另外实例Bean
  84. *void
  85. */
  86. publicvoidtestGetDtoArrFromJsonArrStr2(){
  87. Stringjson="[{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]";
  88. MapclassMap=newHashMap();
  89. classMap.put("data",Person.class);
  90. Object[]objArr=JsonUtil.getDtoArrFromJsonArrStr(json,MyBean.class,classMap);
  91. for(inti=0;i<objArr.length;i++){
  92. System.out.println(((MyBean)objArr[i]).getData().get(0).getClass()
  93. +"name="
  94. +((Person)((MyBean)objArr[i]).getData().get(0)).getName());
  95. }
  96. /*print:
  97. classcomm.test.Personname=get
  98. classcomm.test.Personname=set
  99. */
  100. }
  101. /**
  102. *把一个json数组串转换成存放普通类型元素的集合
  103. *void
  104. */
  105. publicvoidtestGetListFromJsonArrStr1(){
  106. Stringjson="['get',1,true,null]";
  107. Listlist=JsonUtil.getListFromJsonArrStr(json);
  108. for(inti=0;i<list.size();i++){
  109. System.out.println(list.get(i).getClass()+""+list.get(i));
  110. }
  111. /*print:
  112. classjava.lang.Stringget
  113. classjava.lang.Integer1
  114. classjava.lang.Booleantrue
  115. classnet.sf.json.JSONNullnull
  116. */
  117. }
  118. /**
  119. *把一个json数组串转换成集合,且集合里存放的为实例Bean
  120. *void
  121. */
  122. publicvoidtestGetListFromJsonArrStr2(){
  123. Stringjson="[{'name':'get'},{'name':'set'}]";
  124. Listlist=JsonUtil.getListFromJsonArrStr(json,Person.class);
  125. for(inti=0;i<list.size();i++){
  126. System.out.println(list.get(i).getClass()+"name="
  127. +((Person)list.get(i)).getName());
  128. }
  129. /*print:
  130. classcomm.test.Personname=get
  131. classcomm.test.Personname=set
  132. */
  133. }
  134. /**
  135. *把一个json数组串转换成集合,且集合里的对象的属性含有另外实例Bean
  136. *void
  137. */
  138. publicvoidtestGetListFromJsonArrStr3(){
  139. Stringjson="[{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]";
  140. MapclassMap=newHashMap();
  141. classMap.put("data",Person.class);
  142. Listlist=JsonUtil.getListFromJsonArrStr(json,MyBean.class,classMap);
  143. for(inti=0;i<list.size();i++){
  144. System.out.println(((MyBean)list.get(i)).getData().get(0).getClass()
  145. +"name="
  146. +((Person)((MyBean)list.get(i)).getData().get(0)).getName());
  147. }
  148. /*print:
  149. classcomm.test.Personname=get
  150. classcomm.test.Personname=set
  151. */
  152. }
  153. /**
  154. *把json对象串转换成map对象
  155. *void
  156. */
  157. publicvoidtestGetMapFromJsonObjStr(){
  158. Stringjson="{'name':'get','int':1,'double':1.1,'null':null}";
  159. Mapmap=JsonUtil.getMapFromJsonObjStr(json);
  160. for(Iteratoriter=map.keySet().iterator();iter.hasNext();){
  161. System.out.println(map.get(iter.next()).getClass());
  162. }
  163. /*print:
  164. classjava.lang.Double
  165. classnet.sf.json.JSONNull
  166. classjava.lang.Integer
  167. classjava.lang.String
  168. */
  169. }
  170. /**
  171. *把json对象串转换成map对象,且map对象里存放的为其他实体Bean
  172. *void
  173. */
  174. publicvoidtestGetMapFromJsonObjStr2(){
  175. Stringjson="{'data1':{'name':'get'},'data2':{'name':'set'}}";
  176. Mapmap=JsonUtil.getMapFromJsonObjStr(json,Person.class);
  177. for(Iteratoriter=map.keySet().iterator();iter.hasNext();){
  178. Stringkey=(String)iter.next();
  179. System.out.println(map.get(key).getClass()+"name="
  180. +((Person)map.get(key)).getName());
  181. }
  182. /*print:
  183. classcomm.test.Personname=set
  184. classcomm.test.Personname=get
  185. */
  186. }
  187. /**
  188. *把json对象串转换成map对象,且map对象里
  189. *存放的其他实体Bean还含有另外实体Bean
  190. *void
  191. */
  192. publicvoidtestGetMapFromJsonObjStr3(){
  193. Stringjson="{'mybean':{'data':[{'name':'get'}]}}";
  194. MapclassMap=newHashMap();
  195. classMap.put("data",Person.class);
  196. Mapmap=JsonUtil.getMapFromJsonObjStr(json,MyBean.class,classMap);
  197. for(Iteratoriter=map.keySet().iterator();iter.hasNext();){
  198. Stringkey=(String)iter.next();
  199. Objecto=((MyBean)map.get(key)).getData().get(0);
  200. System.out.println(o.getClass()+"name="+((Person)o).getName());
  201. }
  202. /*print:
  203. classcomm.test.Personname=get
  204. */
  205. }
  206. /**
  207. *实体Bean转json串
  208. *void
  209. */
  210. publicvoidtestgetJsonStr1(){
  211. Personps=newPerson();
  212. ps.setDateAttr(newDate());
  213. ps.setName("get");
  214. MyBeanmyBean=newMyBean();
  215. Listlist=newArrayList();
  216. list.add(ps);
  217. myBean.setData(list);
  218. //print:{"data":[{"dateAttr":"2009-09-1207:24:54","name":"get"}]}
  219. System.out.println(JsonUtil.getJsonStr(myBean));
  220. }
  221. /**
  222. *map转json串
  223. *void
  224. */
  225. publicvoidtestgetJsonStr2(){
  226. Personps=newPerson();
  227. ps.setDateAttr(newDate());
  228. ps.setName("get");
  229. Mapmap=newLinkedHashMap();
  230. map.put("person1",ps);
  231. //print:{"person1":{"dateAttr":"2009-09-1207:24:27","name":"get"}}
  232. System.out.println(JsonUtil.getJsonStr(map));
  233. }
  234. /**
  235. *数组转json串
  236. *void
  237. */
  238. publicvoidtestgetJsonStr3(){
  239. Personps=newPerson();
  240. ps.setDateAttr(newDate());
  241. ps.setName("get");
  242. Person[]personArr=newPerson[1];
  243. personArr[0]=ps;
  244. //print:[{"dateAttr":"2009-09-1207:23:54","name":"get"}]
  245. System.out.println(JsonUtil.getJsonStr(personArr));
  246. }
  247. /**
  248. *list转json串
  249. *void
  250. */
  251. publicvoidtestgetJsonStr4(){
  252. Personps=newPerson();
  253. ps.setDateAttr(newDate());
  254. ps.setName("get");
  255. Listlist=newArrayList();
  256. list.add(ps);
  257. //print:[{"dateAttr":"2009-09-1207:22:49","name":"get"}]
  258. System.out.println(JsonUtil.getJsonStr(list));
  259. }
  260. /**
  261. *set转json串
  262. *void
  263. */
  264. publicvoidtestgetJsonStr5(){
  265. Personps=newPerson();
  266. ps.setDateAttr(newDate());
  267. ps.setName("get");
  268. Setset=newLinkedHashSet();
  269. set.add(ps);
  270. //print:[{"dateAttr":"2009-09-1207:22:16","name":"get"}]
  271. System.out.println(JsonUtil.getJsonStr(set));
  272. }
  273. /**
  274. *json对象串转XML
  275. *void
  276. */
  277. publicvoidtestGetXMLFromObj1(){
  278. System.out.println(JsonUtil
  279. .getXMLFromObj("{/"name/":/"json/",/"bool/":true,/"int/":1}"));
  280. /*print:
  281. <?xmlversion="1.0"encoding="UTF-8"?>
  282. <o>
  283. <booltype="boolean">true</bool>
  284. <inttype="number">1</int>
  285. <nametype="string">json</name>
  286. </o>
  287. */
  288. }
  289. /**
  290. *json数组串转XML
  291. *void
  292. */
  293. publicvoidtestGetXMLFromObj2(){
  294. System.out.println(JsonUtil.getXMLFromObj("[1,2,3]"));
  295. /*print:
  296. <?xmlversion="1.0"encoding="UTF-8"?>
  297. <a>
  298. <etype="number">1</e>
  299. <etype="number">2</e>
  300. <etype="number">3</e>
  301. </a>
  302. */
  303. }
  304. /**
  305. *java数组转XML
  306. *void
  307. */
  308. publicvoidtestGetXMLFromObj3(){
  309. Personps=newPerson();
  310. ps.setDateAttr(newDate());
  311. ps.setName("get");
  312. Person[]personArr=newPerson[2];
  313. personArr[0]=ps;
  314. System.out.println(JsonUtil.getXMLFromObj(personArr));
  315. /*print:
  316. <?xmlversion="1.0"encoding="UTF-8"?>
  317. <a>
  318. <eclass="object">
  319. <dateAttrtype="string">2009-09-1206:58:55</dateAttr>
  320. <nametype="string">get</name>
  321. </e>
  322. </a>
  323. */
  324. }
  325. /**
  326. *list转XML
  327. *void
  328. */
  329. publicvoidtestGetXMLFromObj4(){
  330. Personps=newPerson();
  331. ps.setDateAttr(newDate());
  332. ps.setName("get");
  333. Listlist=newArrayList();
  334. list.add(ps);
  335. System.out.println(JsonUtil.getXMLFromObj(list));
  336. /*print:
  337. <?xmlversion="1.0"encoding="UTF-8"?>
  338. <a>
  339. <eclass="object">
  340. <dateAttrtype="string">2009-09-1207:02:31</dateAttr>
  341. <nametype="string">get</name>
  342. </e>
  343. </a>
  344. */
  345. }
  346. /**
  347. *set转XML
  348. *void
  349. */
  350. publicvoidtestGetXMLFromObj5(){
  351. Personps=newPerson();
  352. ps.setDateAttr(newDate());
  353. ps.setName("get");
  354. Setset=newLinkedHashSet();
  355. set.add(ps);
  356. System.out.println(JsonUtil.getXMLFromObj(set));
  357. /*print:
  358. <?xmlversion="1.0"encoding="UTF-8"?>
  359. <a>
  360. <eclass="object">
  361. <dateAttrtype="string">2009-09-1207:04:38</dateAttr>
  362. <nametype="string">get</name>
  363. </e>
  364. </a>
  365. */
  366. }
  367. /**
  368. *map转XML
  369. *void
  370. */
  371. publicvoidtestGetXMLFromObj6(){
  372. Personps=newPerson();
  373. ps.setDateAttr(newDate());
  374. ps.setName("get");
  375. Mapmap=newHashMap();
  376. map.put("person1",ps);
  377. System.out.println(JsonUtil.getXMLFromObj(map));
  378. /*print:
  379. <?xmlversion="1.0"encoding="UTF-8"?>
  380. <o>
  381. <person1class="object">
  382. <dateAttrtype="string">2009-09-1207:08:35</dateAttr>
  383. <nametype="string">get</name>
  384. </person1>
  385. </o>
  386. */
  387. }
  388. /**
  389. *实体Bean转XML
  390. *void
  391. */
  392. publicvoidtestGetXMLFromObj7(){
  393. Personps=newPerson();
  394. ps.setDateAttr(newDate());
  395. ps.setName("get");
  396. System.out.println(JsonUtil.getXMLFromObj(ps));
  397. /*print:
  398. <?xmlversion="1.0"encoding="UTF-8"?>
  399. <o>
  400. <dateAttrtype="string">2009-09-1207:13:02</dateAttr>
  401. <nametype="string">get</name>
  402. </o>
  403. */
  404. }
  405. /**
  406. *从XML对象串转json串
  407. *void
  408. */
  409. publicvoidtestGetJsonStrFromXML1(){
  410. Stringxml="<o><dateAttrtype='string'>2009-09-1207:13:02</dateAttr>"
  411. +"<nametype='string'>get</name></o>";
  412. //print:{"dateAttr":"2009-09-1207:13:02","name":"get"}
  413. System.out.println(JsonUtil.getJsonStrFromXML(xml));
  414. }
  415. /**
  416. *从XML数组串转json串
  417. *void
  418. */
  419. publicvoidtestGetJsonStrFromXML2(){
  420. Stringxml="<aclass='array'><eclass='object'><dateAttrtype='string'>2009-09-1207:04:38</dateAttr>"
  421. +"<nametype='string'>get</name></e></a>";
  422. //print:[{"dateAttr":"2009-09-1207:04:38","name":"get"}]
  423. System.out.println(JsonUtil.getJsonStrFromXML(xml));
  424. }
  425. }

你可能感兴趣的:(java,json,bean)