码迷,mamicode.com
首页 > Web开发 > 详细

日志——JSON的相关方法

时间:2016-08-23 14:37:09      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

http://www.cnblogs.com/henryxu/archive/2013/03/10/2952738.html

JSON  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
 1 /**
 2       * 从json数组中得到相应java数组
 3       * JSONArray下的toArray()方法的使用
 4       * @param str
 5       * @return
 6       */
 7       public static Object[] getJsonToArray(String str) {
 8           JSONArray jsonArray = JSONArray.fromObject(str);
 9           return jsonArray.toArray();
10       }
11 
12    public static void main(String[] args) {        
13         JSONArray jsonStrs = new JSONArray();
14         jsonStrs.add(0, "cat");
15         jsonStrs.add(1, "dog");
16         jsonStrs.add(2, "bird");
17         jsonStrs.add(3, "duck");
18         
19         Object[] obj=getJsonToArray(jsonStrs.toString());
20         for(int i=0;i<obj.length;i++){
21               System.out.println(obj[i]);
22         }
23     }
 1 package jsontest;
 2 
 3 import net.sf.json.JSONArray;
 4 import net.sf.json.JSONObject;
 5 
 6 public class JSONObjectSample {
 7 
 8     // 创建JSONObject对象
 9     private static JSONObject createJSONObject() {
10         JSONObject jsonObject = new JSONObject();
11         jsonObject.put("username", "huangwuyi");
12         jsonObject.put("sex", "男");
13         jsonObject.put("QQ", "413425430");
14         jsonObject.put("Min.score", new Integer(99));
15         jsonObject.put("nickname", "梦中心境");
16         return jsonObject;
17     }
18 
19     public static void main(String[] args) {
20         JSONObject jsonObject = JSONObjectSample.createJSONObject();//静待方法,直接通过类名+方法调用
21         // 输出jsonobject对象
22         System.out.println("jsonObject:" + jsonObject);
23 
24         // 判读输出对象的类型
25         boolean isArray = jsonObject.isArray();
26         boolean isEmpty = jsonObject.isEmpty();
27         boolean isNullObject = jsonObject.isNullObject();
28         System.out.println("是否为数组:" + isArray + ", 是否为空:" + isEmpty
29                 + ", isNullObject:" + isNullObject);
30 
31         // 添加属性,在jsonObject后面追加元素。
32         jsonObject.element("address", "福建省厦门市");
33         System.out.println("添加属性后的对象:" + jsonObject);
34 
35         // 返回一个JSONArray对象
36         JSONArray jsonArray = new JSONArray();
37         jsonArray.add(0, "this is a jsonArray value");
38         jsonArray.add(1, "another jsonArray value");
39         jsonObject.element("jsonArray", jsonArray);
40         //在jsonObject后面追加一个jsonArray
41         JSONArray array = jsonObject.getJSONArray("jsonArray");
42         System.out.println(jsonObject);
43         
44         
45         System.out.println("返回一个JSONArray对象:" + array);
46         // 添加JSONArray后的值
47         // {"username":"huangwuyi","sex":"男","QQ":"413425430","Min.score":99,"nickname":"梦中心境","address":"福建省厦门市","jsonArray":["this is a jsonArray value","another jsonArray value"]}
48         System.out.println("结果=" + jsonObject);
49 
50         // 根据key返回一个字符串
51         String username = jsonObject.getString("username");
52         System.out.println("username==>" + username);
53 
54         // 把字符转换为 JSONObject
55         String temp = jsonObject.toString();
56         JSONObject object = JSONObject.fromObject(temp);
57         // 转换后根据Key返回值
58         System.out.println("qq=" + object.get("QQ"));
59 
60     }
61 
62 }

 

JAVA解析JSON数据

在网页中想后台传递多个数据时,有时数据还是多个动态列表,数据很复杂时,JavaScript程序员喜欢把他们作为json串进行处理,后台收到后需要对json字符串进行解析,幸好有JSON-lib,这个Java类包用于把bean,map和XML转换成JSON并能够把JSON转回成bean和DynaBean。
下载地址:http://json-lib.sourceforge.net/

  1 public class Test {
  2 
  3 /**
  4 
  5 * @param args
  6 
  7 * @author wen
  8 
  9 */
 10 
 11 public static void main(String[] args) {
 12 
 13 //            test1();
 14 
 15 //            test2();
 16 
 17 String json = “{1:{1:{jhinfo:[‘计划一‘,‘亲亲宝宝‘,‘www.wenhq.com‘],jhrate:[‘1-5:10.0‘,‘6-100:5.0/1‘]},2:{jhinfo:[‘计划二‘,‘亲亲宝宝‘,‘www.wenhq.com‘],jhrate:[‘1-100:100.0‘]},3:{jhinfo:[‘计划三‘,‘亲亲宝宝‘,‘www.wenhq.com‘],jhrate:[‘1-100:150.0/7‘]}},2:{4:{jhinfo:[‘年计划‘,‘亲亲宝宝‘,‘www.wenhq.com‘],jhrate:[‘365-365:1000.0‘]}}}”;
 18 
 19 try {
 20 
 21 JSONObject jsonObject = JSONObject.fromObject(json);
 22 
 23 String name = jsonObject.getString(“1″);
 24 
 25 String address = jsonObject.getString(“2″);
 26 
 27 System.out.println(“name is:” + name);
 28 
 29 System.out.println(“address is:” + address);
 30 
 31 Iterator it=jsonObject.keys();
 32 
 33 while (it.hasNext()){
 34 
 35 System.out.println(jsonObject.get(it.next()));
 36 
 37 }
 38 
 39 } catch (JSONException e) {
 40 
 41 e.printStackTrace();
 42 
 43 }
 44 
 45 }
 46 
 47 /**
 48 
 49 * json对象字符串转换
 50 
 51 * @author wen
 52 
 53 */
 54 
 55 private static void test2() {
 56 
 57 String json = “{‘name’: ‘亲亲宝宝’,‘array’:[{‘a‘:‘111‘,‘b‘:‘222‘,‘c‘:‘333‘},{},{‘a‘:‘999‘}],’address’:‘亲亲宝宝’}”;
 58 
 59 try {
 60 
 61 JSONObject jsonObject = JSONObject.fromObject(json);
 62 
 63 String name = jsonObject.getString(“name”);
 64 
 65 String address = jsonObject.getString(“address”);
 66 
 67 System.out.println(“name is:” + name);
 68 
 69 System.out.println(“address is:” + address);
 70 
 71 JSONArray jsonArray = jsonObject.getJSONArray(“array”);
 72 
 73 for (int i = 0; i < jsonArray.size(); i++) {
 74 
 75 System.out.println(“item ” + i + ” :” + jsonArray.getString(i));
 76 
 77 }
 78 
 79 } catch (JSONException e) {
 80 
 81 e.printStackTrace();
 82 
 83 }
 84 
 85 }
 86 
 87 /**
 88 
 89 * json数组 转换,数组以[开头
 90 
 91 * @author wen
 92 
 93 */
 94 
 95 private static void test1() {
 96 
 97 boolean[] boolArray = new boolean[]{true,false,true};
 98 
 99 JSONArray jsonArray1 = JSONArray.fromObject( boolArray );
100 
101 System.out.println( jsonArray1 );
102 
103 // prints [true,false,true]
104 
105 List list = new ArrayList();
106 
107 list.add( “first” );
108 
109 list.add( “second” );
110 
111 JSONArray jsonArray2 = JSONArray.fromObject( list );
112 
113 System.out.println( jsonArray2 );
114 
115 // prints ["first","second"]
116 
117 JSONArray jsonArray3 = JSONArray.fromObject( “[‘json‘,‘is‘,‘easy‘]” );
118 
119 System.out.println( jsonArray3 );
120 
121 // prints ["json","is","easy"]
122 
123 }

 

创建JSONArray的常用四种方法 

1.从头或者从零开始,创建一个JSONArray(Creating a JSONArray from scratch) 
实例1: 


Java代码  
JSONArray jsonArray = new JSONArray().element("JSON").element("1").element("2.0").element("true");   
assertEquals("JSON", jsonArray.getString(0));   
assertEquals(1, jsonArray.getInt(1));   
assertEquals(2.0d, jsonArray.getDouble(2), 0d);   
assertTrue(jsonArray.getBoolean(3));   


3.使用一个Collection来创建一个JSONArray(Creating a JSONArray from a Collection) 
实例1: 

Java代码  
List list = new ArrayList();  
list.add( "JSON" );   
list.add( "1" );   
list.add( "2.0" );   
list.add( "true" );   
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( list ); assertEquals( "JSON", jsonArray.getString(0) );   
assertEquals( 1, jsonArray.getInt(1) );   
assertEquals( 2.0d, jsonArray.getDouble(2), 0d );   
assertTrue( jsonArray.getBoolean(3) );   


4.使用一个Array来创建一个JSONArray(Creating a JSONArray from an array) 
实例1: 

Java代码  
Object[] array = new Object[] { "JSON", 1, 2.0, true };   
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(array); assertEquals("JSON", jsonArray.getString(0));  
assertEquals(1, jsonArray.getInt(1));   
assertEquals(2.0d, jsonArray.getDouble(2), 0d);   
assertTrue(jsonArray.getBoolean(3));   
  
//实例2:   
Object[] array = new Object[] { "JSON", 1, 2.0, true };   
JSONArray jsonArray = JSONArray.fromObject(array);   
assertEquals("JSON", jsonArray.getString(0));   
assertEquals(1, jsonArray.getInt(1));   
assertEquals(2.0d, jsonArray.getDouble(2), 0d);   
assertTrue(jsonArray.getBoolean(3));   


由此可见,无论要转换的源是哪种类型,都可以使用(JSONArray) JSONSerializer.toJSON()或JSONArray.fromObject()来转换; 

常用的三种扩展功能 

1.使用一个JSON格式化字符串来创建一个JSONFunction(JavaScript functions)  
实例: 

Java代码  
String str = "{func: function( param ){ doSomethingWithParam(param); }}";   
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str); JSONFunction func = (JSONFunction) jsonObject.get("func"); ArrayAssertions.assertEquals(new String[] { "param" }, func.getParams());   
assertEquals("doSomethingWithParam(param);", func.getText());   

  
注:函数的写法要注意function(){},参数param是可选的! 

2.排除一个JSON格式化字符串的某些属性(Exclude properties) 
实例: 

Java代码  
String str = "{‘string‘:‘JSON‘, ‘integer‘: 1, ‘double‘: 2.0, ‘boolean‘: true}";   
JsonConfig jsonConfig = new JsonConfig();   
jsonConfig.setExcludes(new String[] { "double", "boolean" }); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str, jsonConfig);   
assertEquals("JSON", jsonObject.getString("string"));   
assertEquals(1, jsonObject.getInt("integer"));  
assertFalse(jsonObject.has("double"));   
assertFalse(jsonObject.has("boolean"));   


3.排除一个JSON格式化字符串的某些属性,使用过滤器(Exclude properties (with filters) 
实例: 
Java代码  
String str = "{‘string‘:‘JSON‘, ‘integer‘: 1, ‘double‘: 2.0, ‘boolean‘: true}";  
JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter(new PropertyFilter() {   
   public boolean apply(Object source, String name, Object value) {  
         if ("double".equals(name) || "boolean".equals(name))   
          { return true; }  
              return false; } });   
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str, jsonConfig);   
assertEquals("JSON", jsonObject.getString("string"));   
assertEquals(1, jsonObject.getInt("integer"));   
assertFalse(jsonObject.has("double"));   
assertFalse(jsonObject.has("boolean"));   


JSONObject-Java常用的四种用法 
1.JSONObject to DynaBean 

Java代码  
String json = "{name=\"json\",bool:true,int:1,double:2.2}"; JSONObject jsonObject = JSONObject.fromObject(json); //抽象的写法:DynaBean bean = (DynaBean) JSONSerializer.toJava( jsonObject ); Object bean = JSONObject.toBean(jsonObject);   
//Object bean1 = JSONSerializer.toJava(jsonObject);   
assertEquals(jsonObject.get("name"), PropertyUtils.getProperty(bean, "name"));  
assertEquals(jsonObject.get("bool"), PropertyUtils.getProperty(bean, "bool"));   
assertEquals(jsonObject.get("int"), PropertyUtils.getProperty(bean, "int"));   
assertEquals(jsonObject.get("double"), PropertyUtils.getProperty(bean, "double"));   


2.JSONObject to JavaBean 

Java代码  
String json = "{name:\"zhangsan\",age:25,hight:1.72,sex:true}"; JSONObject jsonObject = JSONObject.fromObject(json);   
UserBean bean = (UserBean) JSONObject.toBean(jsonObject, UserBean.class);   
System.out.println(jsonObject);   


3.JSONArray to List 

Java代码  
String json = "[\"first\",\"second\"]";   
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json);  
List output = (List) JSONSerializer.toJava(jsonArray);   


4.JSONArray to array 

Java代码  
String json = "[\"first\",\"second\"]";  
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json); JsonConfig jsonConfig = new JsonConfig();  
jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);   
Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);   
Object[] expected = new Object[] { "first", "second" }; ArrayAssertions.assertEquals(expected, output);    


理论上,这样就可以了,但时,有异常Caused by: java.lang.NoSuchMethodException: com.json.Json$UserBean.<init>() 
   
2.使用一个JSON格式化字符串来创建一个JSONArray(Creating a JSONArray from a JSON formatted string)  
实例1: 

Java代码  
String str = "[‘JSON‘, 1, 2.0, true]"; //注意该字符串的格式"[ , ]" JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( str ); assertEquals( "JSON", jsonArray.getString(0) );   
assertEquals( 1, jsonArray.getInt(1) );   
assertEquals( 2.0d, jsonArray.getDouble(2), 0d );   
assertTrue( jsonArray.getBoolean(3) );   


Java代码  
List<String> list = new ArryList<String>(); list.add("a"); list.add("b"); Map<String,List<String>> map = new HashMap<String,List<String>>(); map.put("list",list); MessageUtils.outputJSONResult(JSONObject.fromObject(map).toString(), response); public class MessageUtils { public static void outputJSONResult(String result, HttpServletResponse response) { try { response.setHeader("ContentType", "text/json"); response.setCharacterEncoding("utf-8"); PrintWriter pw = response.getWriter(); pw.write(result); pw.flush(); pw.close(); } catch (IOException e) { e.printStackTrace(); } } 

日志——JSON的相关方法

标签:

原文地址:http://www.cnblogs.com/yg6405816/p/5798889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!