标签:json
林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(网络传输速率)。
json是个非常重要的数据结构,在web开发中应用十分广泛。我觉得每个人都应该好好的去研究一下json的底层实现,分析一下json的相关内容,希望大家能有所收获。首先给大家说一下使用json前的准备工作,需要准备下面的六个jar包:
这里我统一下好打包了,可以在这里来下http://download.csdn.net/detail/evankaka/8865633
(4)commons-collections类库是各种集合类和集合工具类的封装。可以从这里下载:http://commons.apache.org/proper/commons-collections/download_collections.cgi
JSON 语法是 JavaScript 对象表示法语法的子集。
数据在名称/值对中
数据由逗号分隔
花括号保存对象
方括号保存数组
JSON 值可以是:
数字(整数或浮点数)
字符串(在双引号中)
逻辑值(true 或 false)
数组(在方括号中)
对象(在花括号中)
null
对象和数组。
对象结构以”{”大括号开始,以”}”大括号结束。中间部分由0或多个以”,”分隔的”key(关键字)/value(值)”对构成,关键字和值之间以”:”分隔,语法结构如代码。
{ key1:value1, key2:value2, ... }如
{"department":"产品研发","name":"小王","age":23}
其中关键字是字符串,而值可以是字符串,数值,true,false,null,对象或数组
数组结构以”[”开始,”]”结束。中间由0或多个以”,”分隔的值列表组成,语法结构如代码。
[ { key1:value1, key2:value2 }, { key3:value3, key4:value4 } ]如:
[{"department":"产品研发","name":"小王","age":23},{"department":"产品研发","name":"小王","age":23}]
整个工程目录 如下 :
Employer.java如下
package com.mucfc.json; import net.sf.json.JSONString; public class Employer { private String name; private Integer age; private String department; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } @Override public String toString() { return "Employer [name=" + name + ", age=" + age + ", department=" + department + "]"; } /* @Override 要调用这个方法请implements JSONString public String toJSONString() { return "{\"name\":\"" + name + "\",\"department\":\"" + department + "\"}"; }*/ }
package com.mucfc.json; import java.util.ArrayList; import java.util.HashMap; 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.PropertyFilter; /** *Json使用方法总结 *@author linbingwen(博客:http://blog.csdn.net/evankaka) *@since 2015.7.3 */ public class JsonTest { public static void main(String args[]){ beanToJson(); beanToJson1(); beanToJson2(); arrayToJson(); listToJson(); mapToJson(); } /** * bean对象转json * @return void */ public static void beanToJson(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("产品研发"); JSONObject json = JSONObject.fromObject(employer); System.out.println("-----------------------------------------beanToJson() 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson() 结束------------------------------------------------"); } /** * bean对象转json,带过滤器 * @return void */ public static void beanToJson1(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("产品研发"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(new String[] { "age" }); JSONObject json = JSONObject.fromObject(employer, jsonConfig); System.out.println("-----------------------------------------beanToJson1()带过滤器 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson1()带过滤器 结束------------------------------------------------"); } /** * bean对象转json,带过滤器 * @return void */ public static void beanToJson2(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("产品研发"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { return source instanceof Employer && name.equals("age"); } }); JSONObject json = JSONObject.fromObject(employer, jsonConfig); System.out.println("-----------------------------------------beanToJson2() 带过滤器 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson2() 带过滤器 结束------------------------------------------------"); } /** * array对象转json * @return void */ public static void arrayToJson(){ Employer employer1=new Employer(); employer1.setName("小王"); employer1.setAge(23); employer1.setDepartment("产品研发"); Employer employer2=new Employer(); employer2.setName("小王"); employer2.setAge(23); employer2.setDepartment("产品研发"); Employer[] employers=new Employer[]{employer1,employer2}; JSONArray json = JSONArray.fromObject(employers); System.out.println("-----------------------------------------arrayToJson() 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------arrayToJson() 结束------------------------------------------------"); } /** * list对象转json * @return void */ public static void listToJson(){ List<String> list = new ArrayList<String>(); list.add( "first" ); list.add( "second" ); JSONArray json = JSONArray.fromObject(list); System.out.println("-----------------------------------------listToJson() 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------listToJson() 结束------------------------------------------------"); } /** * map对象转json * @return void */ public static void mapToJson(){ Map<Object,Object> map = new HashMap<Object,Object>(); map.put("name", "json"); map.put("bool", Boolean.TRUE); map.put("int", new Integer(1)); map.put("arr", new String[] { "a", "b" }); map.put("func", "function(i){ return this.arr[i]; }"); JSONObject json = JSONObject.fromObject(map); System.out.println("-----------------------------------------mapToJson() 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------mapToJson() 结束------------------------------------------------"); } }
1. Bean转换成json代码
/** * bean对象转json * @return void */ public static void beanToJson(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("产品研发"); JSONObject json = JSONObject.fromObject(employer); System.out.println("-----------------------------------------beanToJson() 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson() 结束------------------------------------------------"); }运行结果如下:
/** * array对象转json * @return void */ public static void arrayToJson(){ Employer employer1=new Employer(); employer1.setName("小王"); employer1.setAge(23); employer1.setDepartment("产品研发"); Employer employer2=new Employer(); employer2.setName("小王"); employer2.setAge(23); employer2.setDepartment("产品研发"); Employer[] employers=new Employer[]{employer1,employer2}; JSONArray json = JSONArray.fromObject(employers); System.out.println("-----------------------------------------arrayToJson() 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------arrayToJson() 结束------------------------------------------------"); }
运行结果如下:
3. List集合转换成json方法
/** * list对象转json * @return void */ public static void listToJson(){ List<String> list = new ArrayList<String>(); list.add( "first" ); list.add( "second" ); JSONArray json = JSONArray.fromObject(list); System.out.println("-----------------------------------------listToJson() 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------listToJson() 结束------------------------------------------------"); }
运行结果如下:
4. Map集合转换成json方法
/** * map对象转json * @return void */ public static void mapToJson(){ Map<Object,Object> map = new HashMap<Object,Object>(); map.put("name", "json"); map.put("bool", Boolean.TRUE); map.put("int", new Integer(1)); map.put("arr", new String[] { "a", "b" }); map.put("func", "function(i){ return this.arr[i]; }"); JSONObject json = JSONObject.fromObject(map); System.out.println("-----------------------------------------mapToJson() 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------mapToJson() 结束------------------------------------------------"); }
运行结果如下:
通常对一个json串和java对象进行互转时,经常会有选择性的过滤掉一些属性值。例如下面的类:
package com.mucfc.json; public class Employer { private String name; private Integer age; private String department; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } @Override public String toString() { return "Employer [name=" + name + ", age=" + age + ", department=" + department + "]"; } }
如果我想过滤age属性怎么办?
方法一:实现JSONString接口
package com.mucfc.json; import net.sf.json.JSONString; public class Employer implements JSONString{ private String name; private Integer age; private String department; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } @Override public String toString() { return "Employer [name=" + name + ", age=" + age + ", department=" + department + "]"; } @Override public String toJSONString() { return "{\"name\":\"" + name + "\",\"department\":\"" + department + "\"}"; } }
方法二:设置jsonconfig实例,对包含和需要排除的属性进行添加或删除。
/** * bean对象转json,带过滤器 * @return void */ public static void beanToJson1(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("产品研发"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(new String[] { "age" }); JSONObject json = JSONObject.fromObject(employer, jsonConfig); System.out.println("-----------------------------------------beanToJson1()带过滤器 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson1()带过滤器 结束------------------------------------------------"); }
/** * bean对象转json,带过滤器 * @return void */ public static void beanToJson2(){ Employer employer=new Employer(); employer.setName("小王"); employer.setAge(23); employer.setDepartment("产品研发"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { return source instanceof Employer && name.equals("age"); } }); JSONObject json = JSONObject.fromObject(employer, jsonConfig); System.out.println("-----------------------------------------beanToJson2() 带过滤器 开始------------------------------------------------"); System.out.println(json.toString()); System.out.println("-----------------------------------------beanToJson2() 带过滤器 结束------------------------------------------------"); }
java工程下载
JSON 最常见的用法之一,是从 web 服务器上读取 JSON 数据(作为文件或作为 HttpRequest),将 JSON 数据转换为 JavaScript 对象,然后在网页中使用该数据。
之前我一直有个困惑,分不清普通字符串
1、json字符串和json对象的区别。
字符串:这个很好解释,指使用“”双引号或’’单引号包括的字符。例如:var comStr = ‘this is string‘;
json字符串:指的是符合json格式要求的js字符串。例如:var jsonStr = "{StudentID:‘100‘,Name:‘tmac‘,Hometown:‘usa‘}";
json对象:指符合json格式要求的js对象。例如:var jsonObj = { StudentID: "100", Name: "tmac", Hometown: "usa" };
2、JSON 实例 - 来自字符串的对象
创建包含 JSON 语法的 JavaScript 字符串:
var txt = ‘{ "employees" : [‘ + ‘{ "firstName":"John" , "lastName":"Doe" },‘ + ‘{ "firstName":"Anna" , "lastName":"Smith" },‘ + ‘{ "firstName":"Peter" , "lastName":"Jones" } ]}‘;
由于 JSON 语法是 JavaScript 语法的子集,JavaScript 函数 eval() 可用于将 JSON 文本转换为 JavaScript 对象。eval() 函数使用的是 JavaScript 编译器,可解析 JSON 文本,然后生成 JavaScript 对象。必须把文本包围在括号中,这样才能避免语法错误:
var obj = eval ("(" + txt + ")");
<!DOCTYPE html> <html> <body> <h2>Create Object from JSON String</h2> <p> First Name: <span id="fname"></span><br> Last Name: <span id="lname"></span><br> </p> <script> var txt = ‘{"employees":[‘ + ‘{"firstName":"John","lastName":"Doe" },‘ + ‘{"firstName":"Anna","lastName":"Smith" },‘ + ‘{"firstName":"Peter","lastName":"Jones" }]}‘; var obj = eval ("(" + txt + ")"); document.getElementById("fname").innerHTML=obj.employees[1].firstName document.getElementById("lname").innerHTML=obj.employees[1].lastName </script> </body> </html>输出结果:
不过eval解析json有安全隐患!现在大多数浏览器(IE8及以上,Chrome和Firefox差不多全部)自带原生JSON对象,提供JSON.parse()方法解析JSON,提供JSON.stringify()方法生成JSON,请使用这两个方法!
如果担心parse()对对象抛异常,可以加一个封装函数:
JSON.pParse = function( tar ) { if( typeof( tar ) === ‘string‘ ) { return JSON.parse( tar ); } else { return tar; } };
//1,从JSON中读数据 function ReadJSON() { alert(obj.key1); alert(obj.key2); alert(obj.person[0].name); //或者alert(obj.person[0]["name"]) alert(obj.object.msg); //或者alert(obj.object["msg"]) }
function Add() { //往JSON对象中增加了一条记录 obj.sex= "男" //或者obj["sex"]="男" alert(obj.sex); }
function Delete() { delete obj.count; }
function Traversal() { for (var c in obj) { console.log(c + ":", obj[c]); } }
版权声明:本文为博主林炳文Evankaka原创文章,未经博主允许不得转载。
标签:json
原文地址:http://blog.csdn.net/evankaka/article/details/46741577