import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSONArray;
/**
* 使用第三方工具,将JavaBean对象/List或Set或Map对象转成JSON
* @author AdminTC
*/
public class TestBean2Json {
private static void javabean2json() {
City city = new City(1,"广州");
JSONArray jSONArray = JSONArray.fromObject(city);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
//[{"id":1,"name":"广州"}]
}
private static void list2json() {
List<City> cityList = new ArrayList<City>();
cityList.add(new City(1,"广州"));
cityList.add(new City(2,"珠海"));
JSONArray jSONArray = JSONArray.fromObject(cityList);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
//[{"id":1,"name":"广州"},{"id":2,"name":"珠海"}]
}
private static void set2json() {
Set<City> citySet = new LinkedHashSet<City>();
citySet.add(new City(1,"广州"));
citySet.add(new City(2,"珠海"));
JSONArray jSONArray = JSONArray.fromObject(citySet);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
//[{"id":1,"name":"广州"},{"id":2,"name":"珠海"}]
}
private static void javabeanlist2json() {
List<City> cityList = new ArrayList<City>();
cityList.add(new City(1,"中山"));
cityList.add(new City(2,"佛山"));
Province province = new Province(1,"广东",cityList);
JSONArray jSONArray = JSONArray.fromObject(province);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
/*
[
{
"id":1,
"name":"广东"
"cityList":[{"id":1,"name":"中山"},{"id":2,"name":"佛山"}],
}
]
*/
}
private static void map2json() {
List<City> cityList = new ArrayList<City>();
cityList.add(new City(1,"中山"));
cityList.add(new City(2,"佛山"));
Map<String,Object> map = new LinkedHashMap<String,Object>();
map.put("total",cityList.size());//表示集合的长度
map.put("rows",cityList);//rows表示集合
JSONArray jSONArray = JSONArray.fromObject(map);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
//[{"total":2,"rows":[{"id":1,"name":"中山"},{"id":2,"name":"佛山"}]}]
jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1);
System.out.println(jsonJAVA);
}
public static void main(String[] args) {
//javabean2json();
//list2json();
//set2json();
//javabeanlist2json();
map2json();
}
}
一)什么是JSON
(1)JSON(Java Script Object Notation(记号,标记))是一种轻量级的数据交换语言,
以文本字符串为基础,且易于让人阅读
注意:XML就是一个重量级的数据交换语言
(2)JSON采用完全独立于任何程序语言的文本格式,使JSON成为理想的数据交换语言
二)JSON的作用
(1)简化创建自定义对象的方式
注意:JSON就是用JS语法来书写,所以必须放在<script>标签中
在用JS语法书写JSON时,最外面不要用""双引号
var p = { id:1, name:"哈哈", tel:[ { no:"135", type:"中移动" }, { no:"133", type:"中联通" } ], show:function(username){ alert("你的姓名是:" + p.name+":"+username); }, isSingle:false }; |
var p = {'city':['北京','上海','广州','深圳']}; for(var i=0;i<p.city.length;i++){ document.write(p.city[i]+"<br/>"); } |
(2)在AJAX中,作为数据载体之一
注意:JS可以直接解析JSON格式的文本,前提是:该JSON必须采用JS格式书写的才行,如果该JSON是采用Java格式写的,必须使用eval()函数转换后,方可被JS解析,该eval("")函数接收一个字符串格式的内容。
(3)省份-城市-区域三级联动【Struts2 + JSON版】
切记:将来JSON是不能完完全全替代XML的,只能在定义对象和数据交换语言方面替代
action:
/** * 根据省份查询城市 */ public String findCityByProvinceMethod() throws Exception{ cityList = new ArrayList<String>(); if("湖北".equals(province)){ cityList.add("武汉"); cityList.add("黄岗"); }else if("湖南".equals(province)){ cityList.add("岳阳"); cityList.add("张家界"); }else if("广东".equals(province)){ cityList.add("韶关"); cityList.add("东莞"); } return "ok"; } /** * 根据城市查询区域 */ public String findAreaByCityMethod() throws Exception{ areaList = new ArrayList<String>(); if("武汉".equals(city)){ areaList.add("AA"); areaList.add("BB"); }else if("黄岗".equals(city)){ areaList.add("CC"); areaList.add("DD"); }else if("岳阳".equals(city)){ areaList.add("EE"); areaList.add("FF"); }else if("张家界".equals(city)){ areaList.add("GG"); areaList.add("HH"); }else if("韶关".equals(city)){ areaList.add("II"); areaList.add("JJ"); }else if("东莞".equals(city)){ areaList.add("KK"); areaList.add("LL"); } return "ok"; } private List<String> cityList; private List<String> areaList; public List<String> getCityList() { return cityList; } public List<String> getAreaList() { return areaList; } |
struts.xml
<package name="provinceCityAreaPackage" extends="json-default" namespace="/"> <action name="findCityByProvinceRequest" class="cn.itcast.javaee.js.provincecityarea.ProvinceCityAreaAction" method="findCityByProvinceMethod"> <result name="ok" type="json"> </result> </action> </package> |
导入:
struts2-json-plugin-2.3.1.1.jar |
三)使用第三方工具,将JavaBean对象/List或Set或Map对象转成JSON
准备导入第三方jar包:
》commons-beanutils-1.7.0.jar
》commons-collections-3.1.jar
》commons-lang-2.5.jar
》commons-logging-1.1.1.jar
》ezmorph-1.0.3.jar
》json-lib-2.1-jdk15.jar
(1)JavaBean----->JSON
》JSONArray jsonArray = JSONArray.fromObject(city);
》String jsonJAVA = jsonArray.toString();
(2)List<JavaBean>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(cityList);
》String jsonJAVA = jsonArray.toString();
(3)List<String>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(stringList);
》String jsonJAVA = jsonArray.toString();
(4)Set<JavaBean>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(citySet);
》String jsonJAVA = jsonArray.toString();
(5)Map<String,Object>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(map);
》String jsonJAVA = jsonArray.toString();
最后一个例子切记,将来jQuery-EasyUI-DataGrid组件时我们还要用到
将来,在企业中,就算脱离struts2的环境,也能用第三方工具,将Java类型转成JSON文本
四)总结JSON的特点
(1)在客户端(特指PC浏览器),直接使用JavaScript语言解析JSON,无需第三方jar包
(2)本质上,就是一个文本,只是该文本有特定的书写格式
(3)可以使用第三方工具,将JavaBean对象或者List/Set/Map<JavaBean>对象转成JSON
(4)优点:JSON与XML很相似,但是它更加轻巧,服务器只需发送一个html普通字符串,不用发送复杂的xml格式文档了
(5)缺点:语法过于严谨,初学者可能觉得代码不易读,写错一点都不行
(6)JSON本质上,就是用JS语法写的特殊文本记号,用JS可以直接解析