一、 总结
它开始于“{”,结束于“}”。每一个属性名和值间用“:”提示,属性间用“,”分隔。一个数组开始于"[",结束于"]",值之间用","分隔。
数组和List转换为JSON用JSONArray.fromObject
Map、bean、beans(保存在一个List中转换)转换为JSON用 JSONObject.fromObject
JSON (JavaScript Object Notation)是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互.
JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON 数据不需要任何特殊的 API 或工具包。
Json必需的包(重新导入包后需重启下,因为这个问题浪费了我好长时间 ,需注意)
commons-beanutils.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
json-lib-2.2.3-jdk13.jar
ezmorph-1.0.6.jar
commons-collections-3.2.1.jar
<script language="javascript"> function showJSON() { var user = { "username":"andy", "age":20, "info": { "tel": "123456", "cellphone": "98765"}, "address": [ {"city":"beijing","postcode":"222333"}, {"city":"newyork","postcode":"555666"} ] } alert(user.username); alert(user.age); alert(user.info.cellphone); //或 user.info["cellphone"] alert(user.address[0].city); alert(user.address[0].postcode); } </script>
这表示一个user对象,拥有username, age, info, address 等属性。
同样也可以用JSON来简单的修改数据,修改上面的例子
js 代码
function showJSON() { var user = { "username":"andy", "age":20, "info": { "tel": "123456", "cellphone": "98765"}, "address": [ {"city":"beijing","postcode":"222333"}, {"city":"newyork","postcode":"555666"} ] } user.username = "Tom"; alert(user.username); }
易错地方 (注意有无外引号):
function testJson(){ var str = { "name": "Violet", "password": "character" }; //JSON类型对象 //无引号,是JSON对象 alert(typeof(str)); //JSON类型 alert(str.password); //alert(obj.toJSONString()); var a=50,b="xxx"; var arr="{id:"+a+",name:'"+b+"'}"; //string类型 //字符串拼接为可转换为JSON的String var str2 = '{ "name": "Violet", "password": "character" }'; //有引号,是String类型对象 alert(typeof(str2)); //string类型 var obj = eval('(' + str2 + ')'); //转换为JSON类型 alert(typeof(obj)); //JSON类型 alert(obj.name); //Violet } </script>
JSONObject resultJSON = new JSONObject(); resultJSON.put("param1", 1); resultJSON.put("param2", 2); resultJSON.put("param3", 3); System.out.println(resultJSON); //{"param1":1,"param2":2,"param3":3}
二、Java代码转换成json代码
1.List集合转换成json代码+
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );
2.Map集合转换成json代码
Map map = new HashMap();
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);
//{"func":function(i){ return this.arr[i]; },"arr":["a","b"],"int":1,"name":"json","bool":true}
3.Bean转换成json代码
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
//当是对象的时候
Student student = new Student();
student.setAge(18);
student.setName("zhangsan");
student.setSex("male");
JSONObject jsonObject = JSONObject.fromObject(student);
System.out.println(jsonObject);//输出{"age":18,"name":"zhangsan","sex":"male"}
4.数组转换成json代码
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
5.beans转换成json代码
List userInfosList = new ArrayList<UserInfo>();
UserInfo u1 = new UserInfo();
u1.setUserId(10000);
u1.setUserName("qqqqq");
u1.setPassword("111111");
UserInfo u2 = new UserInfo();
u2.setUserId(10001);
u2.setUserName("wwwww");
u2.setPassword("222222");
userInfosList.add(u1);
userInfosList.add(u2);
JSONArray json2=JSONArray.fromObject(userInfosList);
Iterator it=json2.listIterator();
while(it.hasNext())
{
JSONObject obj=(JSONObject)it.next();
UserInfo u=(UserInfo)JSONObject.toBean(obj,UserInfo.class);
System.out.println(u.getPassword());
}
6、String转JSON
String listStr = "['apple','orange']"; //JSONArray json = JSONArray.fromObject(listStr); //结果:["apple","orange"] //必须用JSONArray来转,用JSONObject会出现以下错误信息: // A JSONObject text must begin with '{' at character 1 of ['apple','orange'] String mapStr2 = "{'apple','orange'}"; JSONObject json = JSONObject.fromObject(mapStr2); //用JSONObject必须是键值对,上面会出现以下错误: //Expected a ':' after a key at character 9 of {'apple','orange'} String mapStr1 = "{'age':30,'name':'Michael','baby':['Lucy','Lily']}"; JSONObject json2 = JSONObject.fromObject(mapStr1); //{"age":30,"name":"Michael","baby":["Lucy","Lily"]} System.out.println(json);
三、JSON转List、Map
转List: JSONArray.toCollection(json)
//JSON转List String str = "['apple','orange']"; JSONArray json = JSONArray.fromObject(str); Collection<String> list = JSONArray.toCollection(json); for (String s : list) { System.out.println(s); }
转Map:JSONObject.toBean(json , Map.class)
//JOSN转Map String mapStr = "{'age':30,'name':'Michael','baby':['Lucy','Lily']}"; JSONObject json3 = JSONObject.fromObject(mapStr); Map<String, Object> map = (Map) JSONObject.toBean(json3, Map.class); for (Map.Entry<String, Object> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } //name Michael //age 30 //baby [Lucy, Lily]
注意其Str转JSON问题!
四、遍历JSON数据的两种常用方式
var json={"status":1,"info":"u83b7u53d6u6210u529f","data":[{"id":"4","name":"u77f3u5bb6u5e84","information":"u5e02","Region_id":"3","type":"1"}]} var data=json.data; for(i=0;i<data.length;i++) { document.write("Name:"+data[i].name+",Info:"+data[i].information+""); }
var json=[{"kl_id":"2","kl_title":"Test date1","kl_content":"Test date2","kl_type":"3","id":"6"},{"kl_id":"2","kl_title":"Test1","kl_content":"Test2","kl_type":"1","id":"9"}] var str = ""; for (var one in json) { for(var key in json[one]) { str += json[one][key] + ","; } } document.write(str);
List list = query.list(); List<String> excList = new ArrayList<String>(); if(list!=null && list.size()>0){ for (int i = 0; i < list.size(); i++) { Object[] obj = (Object[]) list.get(i); EipAnalysisServiceExc excR=new EipAnalysisServiceExc(); excR.setId(Long.parseLong(obj[0].toString())); excR.setServiceName(obj[1]!=null?obj[1].toString():null); excList.add(JSONObject.fromObject(excR).toString()); } } for (int i = 0; i < excList.size(); i++) { JSONObject jSONObject = JSONObject.fromObject(excList.get(i)); EipAnalysisServiceExc exc = JSONObject.toBean(jSONObject, EipAnalysisServiceExc.class); } /*由JSONObject.fromObject(excR)得到JSONObject对象,然后toString传输,再JSONObject.fromObject解析为JSONObject对象 使用JSONObject.toBean(JSONObject类型,Class类型) // 转换为对象(如自定义类对象,Map对象等) 转换为类类型 */
..