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, "刘仁奎");
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":"刘仁奎"},{"id":2,"name":"牛月月"}]}
{"mapList":[{"编号":"id_0","地址":"Name_0"},{"编号":"id_1","地址":"Name_1"},{"编号":"id_2","地址":"Name_2"}]}
实例1(过滤不想要格式化的字段)
/**
* 依据条件查找全部
*
* @param request
* @param response
*/
@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();
查看原文:http://www.ibloger.net/article/277.html
參考资料
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