Java解析Json对象

来源:互联网 发布:易语言游戏辅助源码 编辑:程序博客网 时间:2024/05/16 12:07

转载来自:http://blog.sina.com.cn/s/blog_67d21ac60100v367.html

一、需要的依赖包


1. commons-beanutils-1.7.0
2. commons-collections-3.1
3. commons-lang-2.3
4. commons-logging-1.0.4
5. ezmorph-1.0.3.jar
6. json-lib-2.4-jdk15.jar
相关链接:
http://json-lib.sourceforge.net/
http://ezmorph.sourceforge.net/
http://morph.sourceforge.net/
http://commons.apache.org/
二、重要的类

JSONObject类:这个类能够将符合Json格式的字符串转化成为严格的Json对象,即JSONObject。同样也能够把Map和自己的 bean对象转换成为严格的Json对象,其应用的就是JSONObject.fromObject( obj)方法了。如果需要把Json对象转换回来的话,就需要new一个JSONObject对象,然后用JSONObject.toBean(jsonObject),然后再把这个Json对象强制转化成为您需要的类型即可,也可以采用    

JSONObject.toBean(jsonObject,pojoCalss),pojoCalss是一个自定义的class或者系统class。

JSONArray类:这个类是把迭代器转化成为JSONObject数组,采用如下方法即可完成 JSONArray.fromObject(jsonString),JSONArray.fromObject(jsonList).如果需要反解析的话,则可以迭代解析或者是直接强制解析,反正JSONArray也是一个迭代起来的。

三、典型例子

java读取本地json文件


Json文件保存在本地硬盘:(如:F:\cctv.json)

格式如下:

    "A":[

          {"name":"xx","sex":"0"}

          ],

    "B":[

          {"address":"xx","phone":"xx"},

          {"address":"xx","phone":"xx"},

          {"address":"xx","phone":"xx"}

        ,

    "C":[

          {"cd":"xx","ph":"xx"},

          {"cd":"xx","ph":"xx"},

          {"cd":"xx","ph":"xx"}

        

要怎么读取Json文件中的数据?A类里面存的是一个Dto对象、B和C都是List集合

方法一:

//json文件存放路径(如:F:\cctv.json)
String data= ReadFile.readFile("F:\\cctv.json");
System.out.println(data);
JSONObject  jsonObj  JSONObject.fromObject(data);
//得到A对象
JSONArray arrayA=jsonObj.getJSONArray("A");
(A) JSONObject.toBean((JSONArray.fromObject(arrayA.toString()).getJSONObject(0)),A.class);
//得到B集合
JSONArray arrayB=jsonObj.getJSONArray("B");
List<B> listB=new ArrayList<B>();
for(int i=0;i<arrayB.size();i++){
b=(B)JSONObject.toBean((JSONArray.fromObject(arrayB.toString()).getJSONObject(i)),B.class);
listB.add(b);
}
//得到C集合
JSONArray arrayC=jsonObj.getJSONArray("C");
List<C> listC=new ArrayList<C>();
for(int i=0;i<arrayB.size();i++){
c=(C)JSONObject.toBean((JSONArray.fromObject(arrayC.toString()).getJSONObject(i)),C.class);
listB.add(c);
}

方法二:

1. 通过java IO 得到文件字符串 String jsonString = “。。。”;
2. JSONObject  jsonObj  = JSONObject.fromObject(jsonString);
3. JSONObject AObj = jsonObj.getJSONObject("A");
4.  A a = JSONObject.toBean(AObj, A.class); 得到A对象
5.  List listB = Array.asList(json.getJSONArray("B").toArray()); 得到B的List集合
6.  List listC = Array.asList(json.getJSONArray("C").toArray()); 得到C的List集合


四、java处理JSON格式数据的工具类


import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

 

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

import net.sf.json.JsonConfig;

import net.sf.json.util.CycleDetectionStrategy;

 

import com.linghui.common.util.DateUtil;

import com.linghui.common.util.jsonutil.DateJsonValueProcessor;

 

public class JsonUtil {

 

 

 public static Object getObject4JsonString(String jsonString,Class pojoCalss){

 Object pojo;

 JSONObject jsonObject = JSONObject.fromObject( jsonString );

 pojo = JSONObject.toBean(jsonObject,pojoCalss);

 return pojo;

 }

 

 

 public static Map getMap4Json(String jsonString){

 JSONObject jsonObject = JSONObject.fromObject( jsonString );

 Iterator keyIter = jsonObject.keys();

 String key;

 Object value;

 Map valueMap = new HashMap();

 while( keyIter.hasNext())

 {

 key = (String)keyIter.next();

 value = jsonObject.get(key);

 valueMap.put(key, value);

 }

 return valueMap;

 }

 

 

 

 public static Object[] getObjectArray4Json(String jsonString){

 JSONArray jsonArray = JSONArray.fromObject(jsonString);

 return jsonArray.toArray();

 }

 

 

 

 public static List getList4Json(String jsonString, Class pojoClass){

 JSONArray jsonArray = JSONArray.fromObject(jsonString);

 JSONObject jsonObject;

 Object pojoValue;

 List list = new ArrayList();

 for ( int i = 0 ; i<jsonArray.size(); i++){

 jsonObject = jsonArray.getJSONObject(i);

 pojoValue = JSONObject.toBean(jsonObject,pojoClass);

 list.add(pojoValue);

  }

 return list;

 }

 

 

 public static String[] getStringArray4Json(String jsonString){

 JSONArray jsonArray = JSONArray.fromObject(jsonString);

 String[] stringArray = new String[jsonArray.size()];

 for( int i = 0 ; i<jsonArray.size() ; i++ ){

 stringArray[i] = jsonArray.getString(i);

 }

 return stringArray;

 }

 

 

 public static Long[] getLongArray4Json(String jsonString){

 JSONArray jsonArray = JSONArray.fromObject(jsonString);

 Long[] longArray = new Long[jsonArray.size()];

 for( int i = 0 ; i<jsonArray.size() ; i++ ){

 longArray[i] = jsonArray.getLong(i);

  }

 return longArray;

 }

 

 

 public static Integer[] getIntegerArray4Json(String jsonString){

 JSONArray jsonArray = JSONArray.fromObject(jsonString);

 Integer[] integerArray = new Integer[jsonArray.size()];

 for( int i = 0 ; i<jsonArray.size() ; i++ ){

 integerArray[i] = jsonArray.getInt(i);

  }

 return integerArray;

 }

 

 

 public static Date[] getDateArray4Json(String jsonString,String DataFormat){

 JSONArray jsonArray = JSONArray.fromObject(jsonString);

 Date[] dateArray = new Date[jsonArray.size()];

 String dateString;

 Date date;

 

 for( int i = 0 ; i<jsonArray.size() ; i++ ){

 dateString = jsonArray.getString(i);

 date = DateUtil.stringToDate(dateString, DataFormat);

 dateArray[i] = date;

 }

 return dateArray;

 }

 

 

 public static Double[] getDoubleArray4Json(String jsonString){

 JSONArray jsonArray = JSONArray.fromObject(jsonString);

 Double[] doubleArray = new Double[jsonArray.size()];

 for( int i = 0 ; i<jsonArray.size() ; i++ ){

 doubleArray[i] = jsonArray.getDouble(i);

 }

 return doubleArray;

 }

 

 

 public static String getJsonString4JavaPOJO(Object javaObj){

 JSONObject json;

 json = JSONObject.fromObject(javaObj);

 return json.toString();

  }

 

 

 public static String getJsonString4JavaPOJO(Object javaObj , String dataFormat){

 JSONObject json;

 JsonConfig jsonConfig = configJson(dataFormat);

 json = JSONObject.fromObject(javaObj,jsonConfig);

 return json.toString();

  }

 

 

 public static void main(String[] args) {

 // TODO 自动生成方法存根

 }

 

 

 public static JsonConfig configJson(String datePattern) {

 JsonConfig jsonConfig = new JsonConfig();

 jsonConfig.setExcludes(new String[]{""});

 jsonConfig.setIgnoreDefaultExcludes(false);

 jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

 jsonConfig.registerJsonValueProcessor(Date.class,

 new DateJsonValueProcessor(datePattern)); 

 return jsonConfig;

 }

 

 

 public static JsonConfig configJson(String[] excludes,

 String datePattern) {

 JsonConfig jsonConfig = new JsonConfig();

 jsonConfig.setExcludes(excludes);

 jsonConfig.setIgnoreDefaultExcludes(false);

 jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

 jsonConfig.registerJsonValueProcessor(Date.class,

 new DateJsonValueProcessor(datePattern)); 

 return jsonConfig;

 }

}

 

package com.linghui.common.util.jsonutil;

 

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

 

import net.sf.json.JsonConfig;

import net.sf.json.processors.JsonValueProcessor;

 

public class DateJsonValueProcessor implements JsonValueProcessor {

 

 public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";

 private DateFormat dateFormat;

 

 

 public DateJsonValueProcessor(String datePattern) { 

 if( null == datePattern )

 dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);

 else

 dateFormat = new SimpleDateFormat(datePattern);

  }

 

 

 

 public Object processArrayValue(Object arg0, JsonConfig arg1) {

 // TODO 自动生成方法存根

 return process(arg0);

 }

 

 

 public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {

 // TODO 自动生成方法存根

 return process(arg1);

 }

 private Object process(Object value) {

 return dateFormat.format((Date) value);

 

0 0