[转]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 ...
随机推荐
- 【Git/GitHub学习笔记】基本操作——创建仓库,本地、远程同步等
近日想分享一些文件,但是用度盘又太麻烦了(速度也很恶心).所以突发奇想去研究了下GitHub的仓库,这篇文章也就是一个最最最基础的基本操作.基本实现了可以在GitHub上存储文本信息与代码. 由于我的 ...
- GCC在C语言中内嵌汇编 asm __volatile__ 【转】
转自:http://blog.csdn.net/pbymw8iwm/article/details/8227839 在内嵌汇编中,可以将C语言表达式指定为汇编指令的操作数,而且不用去管如何将C语言表达 ...
- yml格式
是什么? yml文件扩展名是YAML的缩写,YAML于2001年出现,是一种数据描述语言,和xml类似 为什么用它? 我们在做javaweb项目的时候最常见的就是.xml配置文件和properitie ...
- ES6 module语法加载 import export
export:暴露,就是把接口暴露出去 import:引入,跟字面意思一样,引入接口 export {} export function demo(){} export var demo1; 这上面的 ...
- php上传文件常见错误
今天在文件上传过程中遇到的文件上传不过去,和网页报错,最后经查看总结有以下几个方面 上传文件错误码 error=0 正常上传 error=1 上传的大小超过了input[type=file]的文件上传 ...
- 【转载】python 特殊函数 dunder function
python的特殊方法:另外一种称谓是 dunder function, 就是 under-under function的简写,就是指那些前后都带双下划线的函数. 转自这里: https://blog ...
- WordPress固定链接设置的几种方法(推荐/%post_id%.html)
传说中,固定链接有SEO功能,今天试了试,现在给大家分享一下: wordpress固定链接设置技巧: 1.不要让日期出现在固定链接里面 这基于两个方面的考虑.一是如果数字出现在固定链接里面,等于提醒搜 ...
- bzoj 1477 扩展欧几里德
思路:很裸的求相遇问题. #include<bits/stdc++.h> #define LL long long #define fi first #define se second # ...
- CentOS为中文显示
[sudo yum groupinstall chinese-support]命令即可安装
- 文件权限之facl丶文件属性丶特殊权限
(1)facl:文件的访问控制列表 作用:对象目录或文件可以对不同的用户设定不同的权限 1)getfacl:查看文件或目录的访问控制列表权限 查看 getfacl file/dir acl权限特征:如 ...