JS中使用JSON
JSON对象 --> JSON字符串:JSON.stringify(对象)
JSON字符串 --> JSON对象:JSON.parse(JSON字符串)
1 <script type="text/javascript"> 2 var json={"name":"chen","age":18,"date":new Date(),"school":null,"hobby":[1,2,3],"gender":true}; 3 document.write(typeof json+"<br>");//object 4 document.write(json+"<br>");//[object Object] 5 document.write(json.name+"<br>");//chen 6 document.write(json.hobby[0]+"<br>");//1 7 document.write("JSON转化成string<br>"); 8 var jsonStr=JSON.stringify(json); 9 document.write(typeof jsonStr+"<br>");//string 10 document.write(jsonStr+"<br>");//{"name":"chen","age":18,"date":"2017-08-17T13:15:32.981Z","school":null,"hobby":[1,2,3],"gender":true} 11 //document.write(jsonStr.name+"<br>");//undefined出错 12 //document.write(jsonStr.hobby[0]+"<br>");//undefined出错 13 document.write("string转化成JSON<br>"); 14 var jsonObj=JSON.parse(jsonStr); 15 document.write(typeof jsonObj+"<br>");//object 16 document.write(jsonObj+"<br>");//[object Object] 17 document.write(jsonObj.name+"<br>");//chen 18 document.write(jsonObj.hobby[0]+"<br>");//1 19 </script>
JAVA中使用JSON
目前Java中用的比较多的JSON解析工具:
- json-lib --> 使用麻烦,解析性能最差
- Jackson --> 使用较麻烦,解析性能最好
- Gson --> 使用简单,解析性能中等
- Gson是谷歌出的一款JSON解析工具,使用简单,且性能较好。
GSON工具类的使用
1 // 将普通对象转换为JSON字符串! 2 Student stu = new Student("尘", 18); 3 System.out.println(stu);//com.test.Student@15db9742-----内存地址 4 Gson gson = new Gson(); 5 String json = gson.toJson(stu); 6 System.out.println(json);//{"name":"尘","age":18} 7 Student fromJson1 = gson.fromJson(json, Student.class); 8 System.out.println(fromJson1);//com.test.Student@25f38edc-----内存地址 9 10 // 把Map转换成JSON字符串 11 Map<String,String> map2 = new HashMap<String,String>(); 12 map2.put("hobby","篮球"); 13 map2.put("gender", "男"); 14 String json2 = gson.toJson(map2); 15 System.out.println(json2);//{"gender":"男","hobby":"篮球"} 16 Map<String,String> fromJson2 = gson.fromJson(json2, Map.class); 17 System.out.println(fromJson2);//{gender=男, hobby=篮球} 18 19 // 将List转换为JSON字符串 20 List<Student> list = new ArrayList<Student>(); 21 list.add(new Student("Tom", 7)); 22 list.add(new Student("Jerry", 5)); 23 String json3 = gson.toJson(list); 24 System.out.println(json3);//[{"name":"Tom","age":7},{"name":"Jerry","age":5}] 25 List<Map<String, Object>> fromJson3 = gson.fromJson(json3, List.class); 26 for (Map map3 : fromJson3) { 27 System.out.println(map3.get("name")); 28 //Tom 29 //Jerry 30 }
付gson-2.2.4.jar下载地址(百度云) 密码:9ngh