[转]java中JSONObject与JSONArray的使用详细说明及有关JSON的工具类
JSONObject与JSONArray的使用
一、JAR包简介
要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:
1.commons-lang.jar
2.commons-beanutils.jar
3.commons-collections.jar
4.commons-logging.jar
5.ezmorph.jar
6.json-lib-2.2.2-jdk15.jar
二、JSONObject对象使用
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"));
}
}
以下是一个经常使用的工具类,和大家一起分享:
- /**
- * 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;
- }
- }
- /** *//**
- * 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);
- }
- }
[转]java中JSONObject与JSONArray的使用详细说明及有关JSON的工具类的更多相关文章
- java中JSONObject与JSONArray的使用
JSONObject与JSONArray 最近在学习过程中用到了稍微复杂点的json数据需要将json数据解析出来,这里就截取一部分作为例子 1.JSONObject介绍 JSONObject-lib ...
- Java处理JSON的工具类(List、Map和JSON之间的转换)——依赖jsonlib支持Map嵌套
原文链接:http://www.itjhwd.com/java_json/ 代码 package com.itjh.mmp.util; import java.io.BufferedReader; i ...
- java处理json的工具类(list,map和json的之间的转换)
需要下载第三方的jar :net.sf.json import java.io.BufferedReader; import java.io.InputStream; import java.io.I ...
- Java中JSONObject相关操作
maven项目pom配置: <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>js ...
- 深入理解Java中的同步静态方法和synchronized(class)代码块的类锁
一.回顾学习内容 在前面几篇博客中我我们已经理解了synchronized对象锁.对象锁的重入.synchronized方法块.synchronized非本对象的代码块, 链接:https://www ...
- 【转载】JAVA中线程的两种实现方法-实现Runnable接口和继承Thread类
转自: http://blog.csdn.net/sunguangran/article/details/6069317 非常感谢原作者,整理的这么详细. 在java中可有两种方式实现多线程,一种是继 ...
- Java中的equals()和hashCode() - 超详细篇
前言 大家好啊,我是汤圆,今天给大家带来的是<Java中的equals()和hashCode() - 详细篇>,希望对大家有帮助,谢谢 文章纯属原创,个人总结难免有差错,如果有,麻烦在评论 ...
- Java从入门到放弃18---Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法
Java从入门到放弃18—Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法01 Map集合Map集合处理键值映射关系的数据为了方便 ...
- java json转换工具类
在java项目中,通常会用到json类型的转换,常常需要对 json字符串和对象进行相互转换. 在制作自定义的json转换类之前,先引入以下依赖 <!--json相关工具--><de ...
随机推荐
- 【模板】SPOJ FACT0 大数分解 miller-rabin & pollard-rho
http://www.spoj.com/problems/FACT0/en/ 给一个小于1e15的数,将他分解. miller-rabin & pollard-rho模板 #include & ...
- Linux命令--more
more命令,功能类似 cat ,cat命令是整个文件的内容从上到下显示在屏幕上. more会以一页一页的显示方便使用者逐页阅读,而最基本的指令就是按空白键(space)就往下一页显示,按 b 键就会 ...
- nowcoder 提高第六场A题
Solution 60分 因为所有的字母要么全相同要么全不同, 所以两条路径比较字典序只需要比较第一条边就可以, 于是建反图, 在反图上按拓扑序转移就可以. 因为有环, 所以拓扑完入度还是不为0的点答 ...
- 【python】pymongo中正则查询时的转义问题
在查询mongo时用到了正则查询 设字符串为 str = '/ab/cd.ef?g=' 直接用正则查询没有匹配. collection.find({"re":{'$regex' ...
- Linux下几种并发服务器的实现模式
Linux下的几种并发服务器的设计模式 1>单线程或者单进程 相当于短链接,当accept之后,就开始数据的接收和数据的发送,不接受新的连接,即一个server,一个client 不存在并发. ...
- BlockingQueue drainTo()
BlockingQueue BlockingQueue的核心方法:放入数据: offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果Blockin ...
- hdu 1130,hdu 1131(卡特兰数,大数)
How Many Trees? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)T ...
- Matlab处理数据导出Paraview可读的vtk文件(一)
Paraview是一个开源的可视化软件. 用到matlab子程序从这里下载 或者到博客末尾复制粘贴 子程序名为 vtkwrite 示例1: load mri D = squeeze(D); vtkwr ...
- C++使用第三方静态库的方法
以jasoncpp为例 首先在github下载最新的的jasoncpp包并解压 找到类似makefiles的文件编译,一般是打开sln文件使用vs编译(生成解决方案),在build文件中可以找到对应的 ...
- Python中的多进程:fork和multiprocessing
Python的多进程 套路1:os.fork() 先敲段代码: #!/usr/bin/env python3 import os os.fork() print('1111111111') 执行结果: ...