JSONObject與JSONArray的使用java
1、JAR包簡介json
要使程序能夠運行必須引入JSON-lib包,JSON-lib包同時依賴於如下的JAR包:數組
1.commons-lang.jar工具
2.commons-beanutils.jarui
3.commons-collections.jarthis
4.commons-logging.jar .net
5.ezmorph.jarorm
6.json-lib-2.2.2-jdk15.jar對象
2、JSONObject對象使用element
JSON- lib包是一個beans,collections,maps,java arrays 和XML和JSON互相轉換的包。在本例中,咱們將使用JSONObject類建立JSONObject對象,而後咱們打印這些對象的值。爲了使用 JSONObject對象,咱們要引入"net.sf.json"包。爲了給對象添加元素,咱們要使用put()方法。
package com.hwy;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JSONObjectSample {
//建立JSONObject對象
private static JSONObject createJSONObject(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","天涯草");
jsonObject.put("sex", "男");
jsonObject.put("QQ", "1");
jsonObject.put("Min.score", new Integer(99));
jsonObject.put("nickname", "天涯草");
return jsonObject;
}
public static void main(String[] args) {
JSONObject jsonObject = JSONObjectSample.createJSONObject();
//輸出jsonobject對象
System.out.println("jsonObject==>"+jsonObject);
//判讀輸出對象的類型
boolean isArray = jsonObject.isArray();
boolean isEmpty = jsonObject.isEmpty();
boolean isNullObject = jsonObject.isNullObject();
System.out.println("isArray:"+isArray+" isEmpty:"+isEmpty+" isNullObject:"+isNullObject);
//添加屬性
jsonObject.element("address", "天涯草");
System.out.println("添加屬性後的對象==>"+jsonObject);
//返回一個JSONArray對象
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, "this is a jsonArray value");
jsonArray.add(1,"another jsonArray value");
jsonObject.element("jsonArray", jsonArray);
JSONArray array = jsonObject.getJSONArray("jsonArray");
System.out.println("返回一個JSONArray對象:"+array);
//添加JSONArray後的值
// {"username":"天涯草","sex":"男","QQ":"天涯草","Min.score":99,"天涯草":"天涯草","address":"天涯草","jsonArray":["this is a jsonArray value","another jsonArray value"]}
System.out.println("結果="+jsonObject);
//根據key返回一個字符串
String username = jsonObject.getString("username");
System.out.println("username==>"+username);
//把字符轉換爲 JSONObject
String temp=jsonObject.toString();
JSONObject object = JSONObject.fromObject(temp);
//轉換後根據Key返回值
System.out.println("qq="+object.get("QQ"));
}
}
如下是一個常用的工具類,和你們一塊兒分享:
Java代碼
- /**
- * Copyright (c) linkwise 2007-2009 corporation.
- * All rights reserved
- */
- package com.linghui.common.util;
-
- 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;
-
- /** *//**
- * @author </br> <a href="mailto:fx19800215@163.com"> robert.feng</a>
- *
- */
- public class JsonUtil ...{
-
- /** *//**
- * 從一個JSON 對象字符格式中獲得一個java對象
- * @param jsonString
- * @param pojoCalss
- * @return
- */
- public static Object getObject4JsonString(String jsonString,Class pojoCalss)...{
- Object pojo;
- JSONObject jsonObject = JSONObject.fromObject( jsonString );
- pojo = JSONObject.toBean(jsonObject,pojoCalss);
- return pojo;
- }
-
-
-
- /** *//**
- * 從json HASH表達式中獲取一個map,改map支持嵌套功能
- * @param jsonString
- * @return
- */
- 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;
- }
-
-
- /** *//**
- * 從json數組中獲得相應java數組
- * @param jsonString
- * @return
- */
- public static Object[] getObjectArray4Json(String jsonString)...{
- JSONArray jsonArray = JSONArray.fromObject(jsonString);
- return jsonArray.toArray();
-
- }
-
-
- /** *//**
- * 從json對象集合表達式中獲得一個java對象列表
- * @param jsonString
- * @param pojoClass
- * @return
- */
- 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;
-
- }
-
- /** *//**
- * 從json數組中解析出java字符串數組
- * @param jsonString
- * @return
- */
- 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;
- }
-
- /** *//**
- * 從json數組中解析出javaLong型對象數組
- * @param jsonString
- * @return
- */
- 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;
- }
-
- /** *//**
- * 從json數組中解析出java Integer型對象數組
- * @param jsonString
- * @return
- */
- 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;
- }
-
- /** *//**
- * 從json數組中解析出java Date 型對象數組,使用本方法必須保證
- * @param jsonString
- * @return
- */
- 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;
- }
-
- /** *//**
- * 從json數組中解析出java Integer型對象數組
- * @param jsonString
- * @return
- */
- 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;
- }
-
-
- /** *//**
- * 將java對象轉換成json字符串
- * @param javaObj
- * @return
- */
- public static String getJsonString4JavaPOJO(Object javaObj)...{
-
- JSONObject json;
- json = JSONObject.fromObject(javaObj);
- return json.toString();
-
- }
-
-
-
-
- /** *//**
- * 將java對象轉換成json字符串,並設定日期格式
- * @param javaObj
- * @param dataFormat
- * @return
- */
- public static String getJsonString4JavaPOJO(Object javaObj , String dataFormat)...{
-
- JSONObject json;
- JsonConfig jsonConfig = configJson(dataFormat);
- json = JSONObject.fromObject(javaObj,jsonConfig);
- return json.toString();
-
-
- }
-
-
-
- /** *//**
- * @param args
- */
- public static void main(String[] args) ...{
- // TODO 自動生成方法存根
-
- }
-
- /** *//**
- * JSON 時間解析器具
- * @param datePattern
- * @return
- */
- 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;
- }
-
- /** *//**
- *
- * @param excludes
- * @param datePattern
- * @return
- */
- 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;
- }
-
- }
Java代碼
- /** *//**
- * linkwise
- */
- 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;
-
-
-
- /** *//**
- * @author </br> <a href="mailto:fx19800215@163.com"> robert.feng</a>
- *
- */
- public class DateJsonValueProcessor implements JsonValueProcessor ...{
-
-
- public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
- private DateFormat dateFormat;
-
-
-
- /** *//**
- * 構造方法.
- *
- * @param datePattern 日期格式
- */
- public DateJsonValueProcessor(String datePattern) ...{
-
- if( null == datePattern )
- dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
- else
- dateFormat = new SimpleDateFormat(datePattern);
-
- }
-
-
-
- /**//* (非 Javadoc)
- * @see net.sf.json.processors.JsonValueProcessor#processArrayValue(java.lang.Object, net.sf.json.JsonConfig)
- */
- public Object processArrayValue(Object arg0, JsonConfig arg1) ...{
- // TODO 自動生成方法存根
- return process(arg0);
- }
-
- /**//* (非 Javadoc)
- * @see net.sf.json.processors.JsonValueProcessor#processObjectValue(java.lang.String, java.lang.Object, net.sf.json.JsonConfig)
- */
- public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) ...{
- // TODO 自動生成方法存根
- return process(arg1);
- }
-
- private Object process(Object value) ...{
- return dateFormat.format((Date) value);
- }
-
-
- }