首页

通过json-lib-jdk.jar包实现对象及List集合转换为JSON字符串的工具类示例代码分享

标签:JSON,json-lib-jdk,对象和json字符串转换,工具类,net.sf.json.JSONArray,JSONObject,ezmorph-1.0.6.jar,myflexjson.jar,commons-lang.jar     发布时间:2017-05-29   

通过net.sf.json.JSONObject、net.sf.json.JSONArray对象、LIST集合转换为JSON字符串(myflexjson.jarezmorph-1.0.6.jarcommons-lang.jarjson-lib-2.3-jdk15.jar全部下载),工具类JsonlibUtil的类具体代码如下所示

import java.util.ArrayList;@b@import java.util.List;@b@import net.sf.json.JSONArray;@b@import net.sf.json.JSONObject;@b@@b@import com.xwood.publisher.persist.PublishVo;@b@@b@public class JsonlibUtil{@b@	@b@	/**@b@	 * 将范型对象转换为字符串@b@	 * @param <T>@b@	 * @param t@b@	 * @return@b@	 */@b@	public  static  <T>  String toJsonString(T t){@b@		return  JSONObject.fromObject(t).toString();  @b@	}@b@	@b@	@b@	/**@b@	 * 将list转换为JSON字符串@b@	 * @param <T>@b@	 * @param list数据集@b@	 * @return@b@	 */@b@	public  static  <T>  String toJsonListString(List<T> list){@b@		return JSONArray.fromObject(list).toString();@b@	}@b@	@b@	@b@	/**@b@	 * 将JSONObject对象转换为cla对象@b@	 * @param <T>@b@	 * @param jsonobj @b@	 * @param cla T对于实体对象class@b@	 * @return@b@	 */@b@	public  static  <T>  T  toObject(JSONObject  jsonobj,Class cla){@b@        return (T)JSONObject.toBean(jsonobj,cla);  @b@	}@b@	@b@@b@	public static void main(String[] args) {@b@		@b@		PublishVo pv1 = new PublishVo();  @b@		pv1.setId("1111");  @b@		pv1.setFileName("fff111");@b@		pv1.setFileDir("fffddd11111");@b@		pv1.setFtpId("fffffdddd1111");@b@		@b@		//打印单对象为字符串@b@		System.out.println("Object:"+JsonlibUtil.toJsonString(pv1));@b@		@b@		PublishVo pv2 = new PublishVo();  @b@		pv2.setId("2222");  @b@		pv2.setFileName("fff2222");@b@		pv2.setFileDir("fffddd2222");@b@		pv2.setFtpId("fffffdddd2222");@b@	          @b@	    List<PublishVo> list = new ArrayList<PublishVo>();  @b@	    list.add(pv1);  @b@	    list.add(pv2);  @b@	    @b@	    //打印list对象为字符串@b@	    System.out.println("List:"+JsonlibUtil.toJsonListString(list));  @b@	    @b@	    @b@	}@b@	@b@}

控制台打印结果如下

Object:{"createTime":"","createUserId":"","fileDir":"fffddd11111","fileName":"fff111","ftpId":"fffffdddd1111","id":"1111","message":"","objectId":"","objectPath":"","objectType":"","publishDate":"","publishEngineType":0,"publishStatus":0,"publishType":"0","siteId":"","status":"","type":"","updateTime":"","updateUserId":"","url":""}
List:[{"createTime":"","createUserId":"","fileDir":"fffddd11111","fileName":"fff111","ftpId":"fffffdddd1111","id":"1111","message":"","objectId":"","objectPath":"","objectType":"","publishDate":"","publishEngineType":0,"publishStatus":0,"publishType":"0","siteId":"","status":"","type":"","updateTime":"","updateUserId":"","url":""},{"createTime":"","createUserId":"","fileDir":"fffddd2222","fileName":"fff2222","ftpId":"fffffdddd2222","id":"2222","message":"","objectId":"","objectPath":"","objectType":"","publishDate":"","publishEngineType":0,"publishStatus":0,"publishType":"0","siteId":"","status":"","type":"","updateTime":"","updateUserId":"","url":""}]
@b@
<<热门下载>>