Java解析JSON



JSON 即 JavaScript Object Natation,它是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。本文将快速讲解 JSON 格式,并通过代码示例演示如何分别在客户端和服务器端进行 JSON 格式数据的处理。


 json-lib和org.json的使用
http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/23/3096001.html


Json必需的包

commons-httpclient-3.1.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
json-lib-2.2.3-jdk13.jar
ezmorph-1.0.6.jar
commons-collections-3.2.1.jar

以上包可以从

http://commons.apache.org/index.html 

http://json-lib.sourceforge.net/ 

http://ezmorph.sourceforge.net/ 

http://morph.sourceforge.net/ 

http://www.docjar.com/ 

中下载到。

出现java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher错误是因为没有导入ezmorph.jar文件或版本不对。

出现java.lang.NoClassDefFoundError: org/apache/commons/collections/map/ListOrderedMap错误是因为没有导入commons-collections.jar文件或版本不对。

Java代码转换成json代码

1.      List集合转换成json代码

List list = new ArrayList();

list.add( "first" );

list.add( "second" );

JSONArray jsonArray2 = JSONArray.fromObject( list );

2.      Map集合转换成json代码

Map map = new HashMap();

map.put("name", "json");

map.put("bool", Boolean.TRUE);

map.put("int", new Integer(1));

map.put("arr", new String[] { "a", "b" });

map.put("func", "function(i){ return this.arr; }");

JSONObject json = JSONObject.fromObject(map);

3.      Bean转换成json代码

JSONObject jsonObject = JSONObject.fromObject(new JsonBean());

4.      数组转换成json代码

boolean[] boolArray = new boolean[] { true, false, true };

JSONArray jsonArray1 = JSONArray.fromObject(boolArray);



5. 一般数据转换成json代码

JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );

6.      beans转换成json代码

List list = new ArrayList();

JsonBean2 jb1 = new JsonBean2();

jb1.setCol(1);

jb1.setRow(1);

jb1.setValue("xx");

JsonBean2 jb2 = new JsonBean2();

jb2.setCol(2);

jb2.setRow(2);

jb2.setValue("");

list.add(jb1);

list.add(jb2);



三、典型例子

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);

 

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值