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

}

以下是一个经常使用的工具类,和大家一起分享:

Java代码 
  1. /**
  2. * Copyright (c) linkwise 2007-2009 corporation.
  3. * All rights reserved
  4. */
  5. package com.linghui.common.util;
  6. import java.util.ArrayList;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.Iterator;
  10. import java.util.List;
  11. import java.util.Map;
  12. import net.sf.json.JSONArray;
  13. import net.sf.json.JSONObject;
  14. import net.sf.json.JsonConfig;
  15. import net.sf.json.util.CycleDetectionStrategy;
  16. import com.linghui.common.util.DateUtil;
  17. import com.linghui.common.util.jsonutil.DateJsonValueProcessor;
  18. /** *//**
  19. * @author </br> <a href="mailto:fx19800215@163.com"> robert.feng</a>
  20. *
  21. */
  22. public class JsonUtil ...{
  23. /** *//**
  24. * 从一个JSON 对象字符格式中得到一个java对象
  25. * @param jsonString
  26. * @param pojoCalss
  27. * @return
  28. */
  29. public static Object getObject4JsonString(String jsonString,Class pojoCalss)...{
  30. Object pojo;
  31. JSONObject jsonObject = JSONObject.fromObject( jsonString );
  32. pojo = JSONObject.toBean(jsonObject,pojoCalss);
  33. return pojo;
  34. }
  35. /** *//**
  36. * 从json HASH表达式中获取一个map,改map支持嵌套功能
  37. * @param jsonString
  38. * @return
  39. */
  40. public static Map getMap4Json(String jsonString)...{
  41. JSONObject jsonObject = JSONObject.fromObject( jsonString );
  42. Iterator  keyIter = jsonObject.keys();
  43. String key;
  44. Object value;
  45. Map valueMap = new HashMap();
  46. while( keyIter.hasNext())
  47. ...{
  48. key = (String)keyIter.next();
  49. value = jsonObject.get(key);
  50. valueMap.put(key, value);
  51. }
  52. return valueMap;
  53. }
  54. /** *//**
  55. * 从json数组中得到相应java数组
  56. * @param jsonString
  57. * @return
  58. */
  59. public static Object[] getObjectArray4Json(String jsonString)...{
  60. JSONArray jsonArray = JSONArray.fromObject(jsonString);
  61. return jsonArray.toArray();
  62. }
  63. /** *//**
  64. * 从json对象集合表达式中得到一个java对象列表
  65. * @param jsonString
  66. * @param pojoClass
  67. * @return
  68. */
  69. public static List getList4Json(String jsonString, Class pojoClass)...{
  70. JSONArray jsonArray = JSONArray.fromObject(jsonString);
  71. JSONObject jsonObject;
  72. Object pojoValue;
  73. List list = new ArrayList();
  74. for ( int i = 0 ; i<jsonArray.size(); i++)...{
  75. jsonObject = jsonArray.getJSONObject(i);
  76. pojoValue = JSONObject.toBean(jsonObject,pojoClass);
  77. list.add(pojoValue);
  78. }
  79. return list;
  80. }
  81. /** *//**
  82. * 从json数组中解析出java字符串数组
  83. * @param jsonString
  84. * @return
  85. */
  86. public static String[] getStringArray4Json(String jsonString)...{
  87. JSONArray jsonArray = JSONArray.fromObject(jsonString);
  88. String[] stringArray = new String[jsonArray.size()];
  89. for( int i = 0 ; i<jsonArray.size() ; i++ )...{
  90. stringArray[i] = jsonArray.getString(i);
  91. }
  92. return stringArray;
  93. }
  94. /** *//**
  95. * 从json数组中解析出javaLong型对象数组
  96. * @param jsonString
  97. * @return
  98. */
  99. public static Long[] getLongArray4Json(String jsonString)...{
  100. JSONArray jsonArray = JSONArray.fromObject(jsonString);
  101. Long[] longArray = new Long[jsonArray.size()];
  102. for( int i = 0 ; i<jsonArray.size() ; i++ )...{
  103. longArray[i] = jsonArray.getLong(i);
  104. }
  105. return longArray;
  106. }
  107. /** *//**
  108. * 从json数组中解析出java Integer型对象数组
  109. * @param jsonString
  110. * @return
  111. */
  112. public static Integer[] getIntegerArray4Json(String jsonString)...{
  113. JSONArray jsonArray = JSONArray.fromObject(jsonString);
  114. Integer[] integerArray = new Integer[jsonArray.size()];
  115. for( int i = 0 ; i<jsonArray.size() ; i++ )...{
  116. integerArray[i] = jsonArray.getInt(i);
  117. }
  118. return integerArray;
  119. }
  120. /** *//**
  121. * 从json数组中解析出java Date 型对象数组,使用本方法必须保证
  122. * @param jsonString
  123. * @return
  124. */
  125. public static Date[] getDateArray4Json(String jsonString,String DataFormat)...{
  126. JSONArray jsonArray = JSONArray.fromObject(jsonString);
  127. Date[] dateArray = new Date[jsonArray.size()];
  128. String dateString;
  129. Date date;
  130. for( int i = 0 ; i<jsonArray.size() ; i++ )...{
  131. dateString = jsonArray.getString(i);
  132. date = DateUtil.stringToDate(dateString, DataFormat);
  133. dateArray[i] = date;
  134. }
  135. return dateArray;
  136. }
  137. /** *//**
  138. * 从json数组中解析出java Integer型对象数组
  139. * @param jsonString
  140. * @return
  141. */
  142. public static Double[] getDoubleArray4Json(String jsonString)...{
  143. JSONArray jsonArray = JSONArray.fromObject(jsonString);
  144. Double[] doubleArray = new Double[jsonArray.size()];
  145. for( int i = 0 ; i<jsonArray.size() ; i++ )...{
  146. doubleArray[i] = jsonArray.getDouble(i);
  147. }
  148. return doubleArray;
  149. }
  150. /** *//**
  151. * 将java对象转换成json字符串
  152. * @param javaObj
  153. * @return
  154. */
  155. public static String getJsonString4JavaPOJO(Object javaObj)...{
  156. JSONObject json;
  157. json = JSONObject.fromObject(javaObj);
  158. return json.toString();
  159. }
  160. /** *//**
  161. * 将java对象转换成json字符串,并设定日期格式
  162. * @param javaObj
  163. * @param dataFormat
  164. * @return
  165. */
  166. public static String getJsonString4JavaPOJO(Object javaObj , String dataFormat)...{
  167. JSONObject json;
  168. JsonConfig jsonConfig = configJson(dataFormat);
  169. json = JSONObject.fromObject(javaObj,jsonConfig);
  170. return json.toString();
  171. }
  172. /** *//**
  173. * @param args
  174. */
  175. public static void main(String[] args) ...{
  176. // TODO 自动生成方法存根
  177. }
  178. /** *//**
  179. * JSON 时间解析器具
  180. * @param datePattern
  181. * @return
  182. */
  183. public static JsonConfig configJson(String datePattern) ...{
  184. JsonConfig jsonConfig = new JsonConfig();
  185. jsonConfig.setExcludes(new String[]...{""});
  186. jsonConfig.setIgnoreDefaultExcludes(false);
  187. jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
  188. jsonConfig.registerJsonValueProcessor(Date.class,
  189. new DateJsonValueProcessor(datePattern));
  190. return jsonConfig;
  191. }
  192. /** *//**
  193. *
  194. * @param excludes
  195. * @param datePattern
  196. * @return
  197. */
  198. public static JsonConfig configJson(String[] excludes,
  199. String datePattern) ...{
  200. JsonConfig jsonConfig = new JsonConfig();
  201. jsonConfig.setExcludes(excludes);
  202. jsonConfig.setIgnoreDefaultExcludes(false);
  203. jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
  204. jsonConfig.registerJsonValueProcessor(Date.class,
  205. new DateJsonValueProcessor(datePattern));
  206. return jsonConfig;
  207. }
  208. }
Java代码 
  1. /** *//**
  2. * linkwise
  3. */
  4. package com.linghui.common.util.jsonutil;
  5. import java.text.DateFormat;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Date;
  8. import net.sf.json.JsonConfig;
  9. import net.sf.json.processors.JsonValueProcessor;
  10. /** *//**
  11. *  @author </br> <a href="mailto:fx19800215@163.com"> robert.feng</a>
  12. *
  13. */
  14. public class DateJsonValueProcessor implements JsonValueProcessor ...{
  15. public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
  16. private DateFormat dateFormat;
  17. /** *//**
  18. * 构造方法.
  19. *
  20. * @param datePattern 日期格式
  21. */
  22. public DateJsonValueProcessor(String datePattern) ...{
  23. if( null == datePattern )
  24. dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
  25. else
  26. dateFormat = new SimpleDateFormat(datePattern);
  27. }
  28. /**//* (非 Javadoc)
  29. * @see net.sf.json.processors.JsonValueProcessor#processArrayValue(java.lang.Object, net.sf.json.JsonConfig)
  30. */
  31. public Object processArrayValue(Object arg0, JsonConfig arg1) ...{
  32. // TODO 自动生成方法存根
  33. return process(arg0);
  34. }
  35. /**//* (非 Javadoc)
  36. * @see net.sf.json.processors.JsonValueProcessor#processObjectValue(java.lang.String, java.lang.Object, net.sf.json.JsonConfig)
  37. */
  38. public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) ...{
  39. // TODO 自动生成方法存根
  40. return process(arg1);
  41. }
  42. private Object process(Object value) ...{
  43. return dateFormat.format((Date) value);
  44. }
  45. }

 

[转]java中JSONObject与JSONArray的使用详细说明及有关JSON的工具类的更多相关文章

  1. java中JSONObject与JSONArray的使用

    JSONObject与JSONArray 最近在学习过程中用到了稍微复杂点的json数据需要将json数据解析出来,这里就截取一部分作为例子 1.JSONObject介绍 JSONObject-lib ...

  2. Java处理JSON的工具类(List、Map和JSON之间的转换)——依赖jsonlib支持Map嵌套

    原文链接:http://www.itjhwd.com/java_json/ 代码 package com.itjh.mmp.util; import java.io.BufferedReader; i ...

  3. java处理json的工具类(list,map和json的之间的转换)

    需要下载第三方的jar :net.sf.json import java.io.BufferedReader; import java.io.InputStream; import java.io.I ...

  4. Java中JSONObject相关操作

    maven项目pom配置: <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>js ...

  5. 深入理解Java中的同步静态方法和synchronized(class)代码块的类锁

    一.回顾学习内容 在前面几篇博客中我我们已经理解了synchronized对象锁.对象锁的重入.synchronized方法块.synchronized非本对象的代码块, 链接:https://www ...

  6. 【转载】JAVA中线程的两种实现方法-实现Runnable接口和继承Thread类

    转自: http://blog.csdn.net/sunguangran/article/details/6069317 非常感谢原作者,整理的这么详细. 在java中可有两种方式实现多线程,一种是继 ...

  7. Java中的equals()和hashCode() - 超详细篇

    前言 大家好啊,我是汤圆,今天给大家带来的是<Java中的equals()和hashCode() - 详细篇>,希望对大家有帮助,谢谢 文章纯属原创,个人总结难免有差错,如果有,麻烦在评论 ...

  8. Java从入门到放弃18---Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法

    Java从入门到放弃18—Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法01 Map集合Map集合处理键值映射关系的数据为了方便 ...

  9. java json转换工具类

    在java项目中,通常会用到json类型的转换,常常需要对 json字符串和对象进行相互转换. 在制作自定义的json转换类之前,先引入以下依赖 <!--json相关工具--><de ...

随机推荐

  1. vuejs怎么在服务器部署?

    通过npm run build 把生成的dist文件夹(不要上传文件夹)里的内容上传到http服务器上就可以通过 http来访问了,开发机上正常,上传以后 程序出现错误不能运行的原因99.99%的可能 ...

  2. Java面试基础知识1

    1.动态绑定是指在执行期间判断所引用对象的实际类型,根据其实际的类型调用其相应的方法. 2.在将超类转换为子类之前,应该使用instanceof进行检查. 3.包含一个或者多个抽象方法的类本身必须被声 ...

  3. python模块(requests,logging)

    一.requests Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythone ...

  4. python基础===函数的几个要点

    函数 可接受任意数量参数的函数 位置参数   和  关键字参数 为了能让一个函数接受任意数量的位置参数,可以使用一个*参数. def avg(first, *r): return (first + s ...

  5. [ python ] 项目二:主机批量管理程序

    开发要求: 1. 对主机进行批量管理    2. 可对单台或主机组批量执行命令    3. 可上传文件到对应的主机或组    4. 使用多线程实现  程序: 1. README # 作者:hkey # ...

  6. NOIP 2011 Day 1

    NOIP 2011 Day 1 tags: NOIP 搜索 categories: 信息学竞赛 总结 铺地毯 选择客栈 Mayan游戏 铺地毯 Solution 因为只会询问一个点被谁覆盖, 而且后面 ...

  7. mysql远程访问cannot connect(10038) 问题解决的过程

    今天用Navicat访问虚拟机上的mysql,无法访问报cannot connect(10038). 首先看是否可以telnet,本机cmd,telnet 192.168.209.128 3306,结 ...

  8. HDU 3045 picnic cows(斜率DP)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3045 题目大意:有n个数,可以把n个数分成若干组,每组不得小于m个数,每组的价值=除了该组最小值以外每 ...

  9. redis之(八)redis的有序集合类型的命令

    [一]增加元素 --->命令:ZADD key score member [score member] --->向有序集合放入一个分数为score的member元素 --->元素存在 ...

  10. nginx反向代理二级页面

    当公司只存在一个公网地址时候,需要影射多个域名,并且域名下面要配置二级目录的时候 可以参照如下配置 upstream h5_game { server 10.0.100.153:80; } serve ...