Json-lib下载及使用
本文介绍用一个类库进行JSON解析。
工具下载地址:http://sourceforge.net/projects/json-lib/?source=directory
下载后,有这么三个东东:
将第一个Jar包导入项目即可用其中的API。
(具体方法:在项目中建立libs文件夹,将第一个包复制进去,然后在Java Build Path里面Add External JARs…)
第二个包是文档,直接右键解压缩之后就会得到html文档,入口是index.html,当然也可以利用工具(jd2chm.exe)将其转换为chm格式这样查看更方便。
第三个包是源码,感兴趣或者以后碰到问题了可以看看。
附加包:解决 Exception in thread "main" java.lang.NoClassDefFoundError
导入了上面的包之后,运行程序会抛出运行时异常:Exception in thread "main" java.lang.NoClassDefFoundError。
搜索之后,才知道还要添加另外的包,我是从这里下载的:
http://download.csdn.net/download/guoyongxue/4423006
如果没有积分,也可以去我的网盘下载:
http://pan.baidu.com/share/link?shareid=1066468750&uk=2701745266
也就是说,一共需要这么多包:
需要把它们全部加入libs文件夹,并且把它们添加进Build Path中。
package com.jsonlib.test; public class Person { private int id; private String name; public Person() { } public Person(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + "]"; } }
测试类
package com.jsonlib.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; public class JSONDataConvert_Test { /** * 创建JSON字符串 * @param key * @param value * @return */ public static String createJsonString(String key, Object value) { JSONObject jsonObject = new JSONObject(); jsonObject.put(key, value); return jsonObject.toString(); } public static void init() { // 一个用户对象转换 Person person = new Person(001,"大美女"); System.out.println(createJsonString("person", person)); // 用户对象集合转换 List<Person> personList = new ArrayList<Person>(); Person person1 = new Person(001, "X-rapido"); Person person2 = new Person(002, "牛月月"); personList.add(person1); personList.add(person2); System.out.println(createJsonString("personList", personList)); // 字符串集合转换 List<String> stringList = new ArrayList<String>(); stringList.add("X-rapido"); stringList.add("NiuYue"); // list中map集合转换 List<Map<String, String>> mapList = new ArrayList<Map<String, String>>(); for (int i = 0; i < 3; ++i) { Map<String, String> map = new HashMap<String, String>(); map.put("编号", "id_" + i); map.put("地址", "Name_" + i); mapList.add(map); } System.out.println(createJsonString("mapList", mapList)); } public static void main(String[] args) { init(); } }
打印输出:
{"person":{"id":1,"name":"大美女"}} {"personList":[{"id":1,"name":"X-rapido"},{"id":2,"name":"牛月月"}]} {"mapList":[{"编号":"id_0","地址":"Name_0"},{"编号":"id_1","地址":"Name_1"},{"编号":"id_2","地址":"Name_2"}]}
实例1(过滤不想要格式化的字段)
/** * 根据条件查找所有 */ @RequestMapping("/findAllKiaAnalysisByCondition") public void findAllKiaAnalysisByCondition(HttpServletRequest request, HttpServletResponse response) { String startDate = request.getParameter("startDate"); String endDate = request.getParameter("endDate"); String unitName = request.getParameter("unitName"); String themes = request.getParameter("themes"); List<KiaAnalysis> listKiaAnalysis = kiaAnalysisService.findAllKiaAnalysisByCondition(startDate, endDate, unitName, themes); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(new String []{"sidaluanjian","cnuisance","roaddamage","sdTrash"}); // 过滤json格式化的字段 String json = JSONArray.fromObject(listKiaAnalysis, jsonConfig).toString(); System.out.println(json); try { response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.print(json); out.close(); } catch (IOException e) { e.printStackTrace(); } }
结果:
[{"rDate":"2014-12","roaddamage":12,"unitName":"学院路"},{"rDate":"2014-12","roaddamage":31,"unitName":"海淀街道"},{"rDate":"2014-12","roaddamage":13,"unitName":"金水路"}]
实例2(过滤Bean对象中字段为空,或字段的值为空的字段)
Test test = new Test(); test.setId("1"); test.setName("zhangsan"); jsonObject.fromobject(test,Test.class).toString; 输出:{"id":"1","name":"zhangsan"}
假如不封装name属性,只封装id属性
Test test = new Test(); test.setId("1"); jsonObject.fromobject(test,Test.class).toString; 输出:{"id":"1","name":""}
如果只输出:{"id":"1"} 这样的json字符,解决方法如下代码
public static void main(String[] args) { Test t = new Test(); t.id = 10; JsonConfig jsonConfig = new JsonConfig(); PropertyFilter filter = new PropertyFilter() { public boolean apply(Object object, String fieldName, Object fieldValue) { return null == fieldValue || "" == fieldValue; } }; jsonConfig.setJsonPropertyFilter(filter); System.out.println(JSONObject.fromObject(t, jsonConfig).toString()); }
如果未给对象赋值用fieldName即可,如果值默认为空,设置fieldValue即可
实例3,把json对象转换简单Bean对象,使用toBean()方法
String jsonString = "{age:'23',country:'china',name:'junxie'}"; JSONObject jsonObject = JSONObject.fromObject(jsonString); User user = (User) JSONObject.toBean(jsonObject, User.class); System.out.println(user.getName()); // 结果:打印的name为 junxie
实例4,把json对象转换复杂bean对象
public class TranslateResult { private String from; // 实际采用的源语言 private String to; // 实际采用的目标语言 private List<ResultPair> trans_result; // 结果体 }
public class ResultPair { private String src; // 原文 private String dst; // 译文 }
main方法
StringBuffer sb = new StringBuffer(); String json = "{\"from\":\"en\",\"to\":\"zh\",\"trans_result\":[{\"src\":\"hello\",\"dst\":\"您好\"},{\"src\":\"beautiful\",\"dst\":\"美女\"}]}"; Map<String, Class<ResultPair>> map = new HashMap<String, Class<ResultPair>>(); map.put("trans_result", ResultPair.class); TranslateResult translateResult = (TranslateResult) JSONObject.toBean(JSONObject.fromObject(json), TranslateResult.class, map); List<ResultPair> list = translateResult.getTrans_result(); for (ResultPair rp : list) { sb.append(rp.getDst()); } System.out.println(sb); // 输出:你好美女
默认json-lib会将Bean的字段首字母小写即便定义时候是大写开头,所以可以使用以下方法将json输出的字段转换为首字母大写
// 使用PropertyNameProcessor处理属性首字母大写问题,默认转换首字母会小写 PropertyNameProcessor propertyNameProcessor = new PropertyNameProcessor() { @Override public String processPropertyName(Class target, String fieldName) { return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); } }; jsonConfig.registerJsonPropertyNameProcessor(V_FirstPaymentMobilePwdIn.class, propertyNameProcessor); String json = JSONObject.fromObject(model,jsonConfig).toString();
参考资料
Json-lib工具类库下载地址:
http://sourceforge.net/projects/json-lib/?source=directory
http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/
附加包下载地址:
http://download.csdn.net/download/guoyongxue/4423006
百度网盘中全部Json-lib资源下载:
http://pan.baidu.com/share/link?shareid=1066468750&uk=2701745266