Java JSON解析的两种常用方式

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


JSONObject必包的Jar包及json生成的简单案例 所有commons包的网址: http://commons.apache.org/index.html 组装和解析JSONObject的Json字符串,共需要下面六个包: 1、json-lib 2、commons-beanutils 3、commons-collections 4、commons-lang 5、commons-logging 6、ezmorph 第零个包: json-lib-2.4-jdk15.jar http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/ 下载地址:http://nchc.dl.sourceforge.net/project/json-lib/json-lib/json-lib-2.4/json-lib-2.4-jdk15.jar 第一个包: commons-beanutils-1.9.2.jar http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi 下载地址:http://mirrors.cnnic.cn/apache//commons/beanutils/binaries/commons-beanutils-1.9.2-bin.zip 第二个包: (注:此包不可用,改用旧包) commons-collections4-4.0.jar http://commons.apache.org/proper/commons-collections/download_collections.cgi 下载地址:http://apache.dataguru.cn//commons/collections/binaries/commons-collections4-4.0-bin.zip (注:此包可用,低版本的包稳定性更高) commons-collections-3.2.1.jar http://commons.apache.org/proper/commons-collections/download_collections.cgi 下载地址:http://mirrors.hust.edu.cn/apache//commons/collections/binaries/commons-collections-3.2.1-bin.zip 第三个包: (注:此包不可用,会造成程序出错,改用旧包) commons-lang3-3.3.2.jar http://commons.apache.org/proper/commons-lang/download_lang.cgi 下载地址:http://apache.dataguru.cn//commons/lang/binaries/commons-lang3-3.3.2-bin.zip (注:此包可用,低版本的包稳定性更高) commons-lang-2.6-bin http://commons.apache.org/proper/commons-lang/download_lang.cgi?Preferred=http%3A%2F%2Fapache.dataguru.cn%2F 下载地址:http://apache.dataguru.cn//commons/lang/binaries/commons-lang-2.6-bin.zip 第四个包: commons-logging-1.1.3.jar http://commons.apache.org/proper/commons-logging/download_logging.cgi 下载地址:http://apache.dataguru.cn//commons/logging/binaries/commons-logging-1.1.3-bin.zip 第五个包: ezmorph-1.0.2.jar http://ezmorph.sourceforge.net/ http://sourceforge.net/projects/ezmorph/files/ezmorph/ 下载地址:http://nchc.dl.sourceforge.net/project/ezmorph/ezmorph/ezmorph-1.0.6/ezmorph-1.0.6.jar
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值