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. 【模板】SPOJ FACT0 大数分解 miller-rabin & pollard-rho

    http://www.spoj.com/problems/FACT0/en/ 给一个小于1e15的数,将他分解. miller-rabin & pollard-rho模板 #include & ...

  2. Linux命令--more

    more命令,功能类似 cat ,cat命令是整个文件的内容从上到下显示在屏幕上. more会以一页一页的显示方便使用者逐页阅读,而最基本的指令就是按空白键(space)就往下一页显示,按 b 键就会 ...

  3. nowcoder 提高第六场A题

    Solution 60分 因为所有的字母要么全相同要么全不同, 所以两条路径比较字典序只需要比较第一条边就可以, 于是建反图, 在反图上按拓扑序转移就可以. 因为有环, 所以拓扑完入度还是不为0的点答 ...

  4. 【python】pymongo中正则查询时的转义问题

    在查询mongo时用到了正则查询 设字符串为   str = '/ab/cd.ef?g=' 直接用正则查询没有匹配. collection.find({"re":{'$regex' ...

  5. Linux下几种并发服务器的实现模式

    Linux下的几种并发服务器的设计模式 1>单线程或者单进程 相当于短链接,当accept之后,就开始数据的接收和数据的发送,不接受新的连接,即一个server,一个client 不存在并发. ...

  6. BlockingQueue drainTo()

    BlockingQueue BlockingQueue的核心方法:放入数据: offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果Blockin ...

  7. hdu 1130,hdu 1131(卡特兰数,大数)

    How Many Trees? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)T ...

  8. Matlab处理数据导出Paraview可读的vtk文件(一)

    Paraview是一个开源的可视化软件. 用到matlab子程序从这里下载 或者到博客末尾复制粘贴 子程序名为 vtkwrite 示例1: load mri D = squeeze(D); vtkwr ...

  9. C++使用第三方静态库的方法

    以jasoncpp为例 首先在github下载最新的的jasoncpp包并解压 找到类似makefiles的文件编译,一般是打开sln文件使用vs编译(生成解决方案),在build文件中可以找到对应的 ...

  10. Python中的多进程:fork和multiprocessing

    Python的多进程 套路1:os.fork() 先敲段代码: #!/usr/bin/env python3 import os os.fork() print('1111111111') 执行结果: ...