JavaWeb——JSON
1、介绍
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。易于人阅读和编写,同时也易于机器解析和生成。JSON采用完全独立于语言的文本格式,而且很多语言都提供了对json的支持(包括C,C++,等),这样就使得JSON成为理想的数据交换语言。
- 轻量级:指的是跟xml做比较的
- 数据交换:客户端和服务器之间业务数据的传输格式
2、JSON在Javascript中的使用(客户端)
2.1、JSON的定义
JSON是由键值对组成,并且由花括号(大括号)包围,每个键由引号引起来,键值对之间使用冒号进行分隔,多组键值对直接使用逗号进行分离
<script type="text/javascript">
var jsonObj={
"key1":12,
"key2":"abc",
"key3":[12,"abc",true],
"key4":{
"key1":11,
"key2":"cba",
}
}
</script>
2.2、JSON的访问
<script type="text/javascript">
alert(jsonObj.key1)
</script>
2.3、json的两个常用方法
1、json对象:我们需要操作数据的时候
2、json字符串:我们要在客户端和服务器之间进行数据交换的时候
JSON.stringify() 把json对象转换成json字符串
JSON.prase() 把json字符串转换成为json对象
<script type="text/javascript">
var string=JSON.stringify(jsonObj)
alert(jsonObj)
</script>
3、JSON在java中的使用(服务器端)
需要导入gson.jar包
3.1、javaBean和json的互换
public void test(){
student dcd = new student("dcd", 18, 41914069);
//创建gson对象实例
Gson gson = new Gson();
String s = gson.toJson(dcd);
System.out.println(s);
student student = gson.fromJson(s, student.class);
System.out.println(student);
}
3.2、list和json的互换
- list转换称为json
public void test1(){
ArrayList<student> students = new ArrayList<>();
students.add(new student("dcd", 18, 41914069));
students.add(new student("lx", 18, 41914069));
students.add(new student("lxj", 18, 41914069));
Gson gson = new Gson();
String s = gson.toJson(students);
System.out.println(s);
}
- json转换list
写一个继承类
public class studentListType extends TypeToken<ArrayList<student>> {
}
再进行转换
public void test1(){
ArrayList<student> students = new ArrayList<>();
students.add(new student("dcd", 18, 41914069));
students.add(new student("lx", 18, 41914069));
students.add(new student("lxj", 18, 41914069));
Gson gson = new Gson();
String s = gson.toJson(students);
System.out.println(s);
List<student> list = gson.fromJson(s, new studentListType().getType());
System.out.println(list.get(0));
}
3.3、map和json的互换
public void test2(){
HashMap<String, String> map = new HashMap<>();
map.put("dcd","np");
map.put("lxj","lj");
Gson gson = new Gson();
String s = gson.toJson(map);
System.out.println(s);
HashMap<String, String> map1= gson.fromJson(s, new TypeToken<HashMap<String, String>>(){}.getType());
System.out.println(map1);
System.out.println(map1.get("dcd"));
}