Java常用的解析JSON的方式有两种,一种是JSON-lib,一种是org.json。
JSON-lib:
依赖包:
commons-beanutils.jar
commons-collections.jar
commons-lang.jar
commons-logging.jar
ezmorph.jar
json-lib.jar
基本方法介绍:
List、数组转换为json
JSONArray.fromObject(list) or JSONArray.fromObject(arr)
Map、bean转换为json
JSONObject.fromObject(map) or JSONObject.fromObject(beanname)
普通字符串转换为json
JSONObject.fromObject("{'name':'zs'}") or JSONArray.fromObject("['zs','ls','ww']")
示例:
package net.hkh.json;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/*
* JSONTest类
*/
public class JSONTest{
/*
* 解析JSON数据
*/
public static void parseJSON(String jsonString){
JSONObject jb=JSONObject.fromObject(jsonString);
JSONObject ja=jb.getJSONArray("employee");
List<Employee>empList=new ArrayList<Employee>();
for(int i=0;i<ja.size();i++){
Employee emp=new Employee();
emp.setName(ja.getJSONObject(i).getString("name"));
emp.setSex(ja.getJSONObject(i).getString("sex"));
emp.setAge(ja.getJSONObject(i).getInt("age"));
empList.add(emp);
}
System.out.println("\n将JSON数据转换为Employee对象:");
for(int i=0;i<empList.size();i++){
Employee emp=empList.get(i);
System.out.println("name:"+emp.getName()+"sex:"+emp.getSex()+"age:"+emp.getAge());
}
}
/*
* 构造JSON数据
*/
public static String buildJSON(){
JSONObject jo=new JSONObject();
Map<String,String>map1=new HashMap<String,String>();
map1.put("name","zs");
map1.put("sex","female");
map1.put("age","23");
Map<String,String>map2=new HashMap<String,String>();
map2.put("name","ls");
map2.put("sex","male");
map2.put("age","24");
List<Map<String,String>>list=new ArrayList<Map<String,String>>();
list.add(map1);
list.add(map2);
Employee emp=new Employee();
emp.setName("ww");
emp.setSex("male");
emp.setAge(25);
JSONArray ja1=JSONArray.fromObject(map1);
JSONArray ja2=JSONArray.fromObject(list);
JSONArray ja3=JSONArray.fromObject(employee);
System.out.println("JSONArray对象数据格式:");
System.out.println(ja1.toString());
System.out.println(ja2.toString());
System.out.println(ja3.toString());
jo.put("map",ja1);
jo.put("employee",ja2);
System.out.println("\n最终构造的JSON数据格式:");
System.out.println(jo.toString());
return jo.toString();
}
/*
* main方法
*/
public static void main(String[]args){
parseJSON(buildJSON());
}
}
/*
* Employee类
*/
class Employee {
private String name ;
private String sex ;
private int age ;
public Employee() {
}
public Employee(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex ;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age ;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return name + "," + sex + "," + age;
}
}
========================================================================
org.json
依赖包:
json.org.jar
基本方法介绍:
org.json不能直接与bean进行转换,需要通过map进行中转
1.将bean转换为Map:
public static Map toMap(Object bean) {
Map rslt = new HashMap();
Method[] methods = bean.getClass().getDeclaredMethods();
for (Method method : methods) {
try {
if (method.getName().startsWith("get")) {
String field = method.getName();
field = field.substring(field.indexOf("get") + 3);
field = field.toLowerCase().charAt(0) + field.substring(1);
Object value = method.invoke(bean, (Object[]) null);
rslt.put(field, null == value ? "" : value.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
return rslt;
}
2.将json转换为Map
public static Map toMap(String jsonString) throws JSONException {
JSONObject obj = new JSONObject(jsonString);
Map rslt = new HashMap();
Iterator iter = obj.keys();
String key = null;
String value = null;
while (iter.hasNext()) {
key = (String) iter.next();
value = obj.getString(key);
rslt.put(key, value);
}
return rslt;
}
3.将Map转换为JavaBean
public static Object toJavaBean(Object bean, Map data) {
Method[] methods = bean.getClass().getDeclaredMethods();
for (Method method : methods) {
try {
if (method.getName().startsWith("set")) {
String field = method.getName();
field = field.substring(field.indexOf("set") + 3);
field = field.toLowerCase().charAt(0) + field.substring(1);
method.invoke(bean, new Object[] { data.get(field) });
}
} catch (Exception e) {
e.printStackTrace();
}
}
return bean;
}
4.将JSON转换为JavaBean
public static Object toJavaBean(Object bean, String jsonString)
throws JSONException {
return toJavaBean(bean, toMap(jsonString));
}
==========================================
json-lib与org.json比较:
1.org.json比json-lib要轻量得多,前者没有依赖其他任何jar包,而后者要依赖ezmorph和commons的lang、loggin、beanutils、collections等组件
2.json-lib在构造bean和解析bean时比org.json要方便得多,json-lib可与JavaBean直接互转,而org.json不能与JavaBean进行直接转换需要通过Map进行中转,即先将JavaBean转换为Map,然后再将Map转换为JavaBean