Map、bean、beans(保存在一个List中转换)转换为JSON用 JSONObject.fromObjectJSONObject.toBean(JSONObject类型,Class类型) // 转换为对象(如自定义类对象,Map对象等)
一、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
JSON的格式
JSON的格式是由大括号和由冒号(:)构成的名值对所组成的。注意JSON格式与对象字面量 (object literals) 的区别:JSON的名字部分严格用引号+名字来表示。
举例说明
- 对象的字面量
var objectLiteral = {
name: "Objector.L",
age: "24",
special: "JavaScript",
sayName: function() {
return this.name;
}
};
- JSON对象
var jsonFormat = {
"summary": "Blogs",
"blogrolls": [
{
"title": "Explore JavaScript",
"link": "http://example.com/"
},
{
"title": "Explore JavaScript",
"link": "http://example.com/"
}
]
};
eval和JSON
由于Ajax的兴起,JSON这种轻量级的数据格式作为客户端与服务器之间的传输格式逐渐地流行起来,进而出现的问题是如何将服务器端构建好的JSON数据转化为可用的JavaScript对象。利用eval函数无疑是一种简单而直接的方法。在转化的时候需要将JSON字符串的外面包装一层圆括号:
var jsonObject = eval("(" + jsonFormat + ")");
为什么要加括号?
加上圆括号的目的是迫使eval函数在评估JavaScript代码的时候强制将括号内的表达式(expression)转化为对象,而不是作为语句(statement)来执行。举一个例子,例如对象字面量{},如若不加外层的括号,那么eval会将大括号识别为JavaScript代码块的开始和结束标记,那么{}将会被认为是执行了一句空语句。所以下面两个执行结果是不同的:
alert(eval("{}"); // return undefined
alert(eval("({})");// return object[Object]
JSON格式的名字部分为什么要加引号?
因为eval函数会将{foo:”bar”}解释成合法的JavaScript语句,而非表达式。但是人们往往想要的是让eval将这段代码解释成一个对象。所以JSON格式会强制你去在名字的外侧加上引号再结合圆括号,这样eval就不会错误的将JSON解释成代码块。
举例说明
- eval错误解析语义
alert(eval('{foo:"bar"}')); // return "bar", incorrect
- eval正确解析JSON
alert(eval('({"foo": "bar"})')); // return JSON object, correct
结论
理解eval的工作原理和json的严格的限定格式,合理结合eval和json应用于JavaScript的数据传递和对象转换。
following this format:
eval('{' + jsonString + ')');// code removed by author at 2010-01-03
eval('(' + jsonString + ')');
<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}
var t="{'firstName': 'cyra', 'lastName': 'richardson'}"; var jsonobj=eval('('+t+')'); alert(jsonobj.firstName); alert(jsonobj.lastName); var t2="[{name:'zhangsan',age:'24'},{name:'lisi',age:'30'},{name:'wangwu',age:'16'},{name:'tianqi',age:'7'}] "; var myobj=eval(t2); //通过eval() 函数可以将JSON字符串转化为对象 for(var i=0;i<myobj.length;i++){ alert(myobj[i].name); alert(myobj[i].age); }
二、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对象等) 转换为类类型 */
..