一、 总结
JSON对象是一个无序的"名称/值"对的集合
它开始于“{”,结束于“}”。每一个属性名和值间用“:”提示,属性间用“,”分隔。一个数组开始于"[",结束于"]",值之间用","分隔。
数组和List转换为JSON用JSONArray.fromObject
Map、bean、beans(保存在一个List中转换)转换为JSON用 JSONObject.fromObject
JSONObject.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
- <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);
-
- 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" };
-
- alert(typeof(str));
- alert(str.password);
-
-
-
- var a=50,b="xxx";
- var arr="{id:"+a+",name:'"+b+"'}";
-
-
- var str2 = '{ "name": "Violet", "password": "character" }';
-
- alert(typeof(str2));
- var obj = eval('(' + str2 + ')');
- alert(typeof(obj));
- alert(obj.name);
- }
- </script>
- JSONObject resultJSON = new JSONObject();
- resultJSON.put("param1", 1);
- resultJSON.put("param2", 2);
- resultJSON.put("param3", 3);
- System.out.println(resultJSON);
-
二、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);
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']";
-
-
-
-
-
- String mapStr2 = "{'apple','orange'}";
- JSONObject json = JSONObject.fromObject(mapStr2);
-
-
-
- String mapStr1 = "{'age':30,'name':'Michael','baby':['Lucy','Lily']}";
- JSONObject json2 = JSONObject.fromObject(mapStr1);
-
-
- System.out.println(json);
三、JSON转List、Map
转List: JSONArray.toCollection(json)
-
- 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)
-
- 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());
- }
-
-
-
注意其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);
。。