了解JSON
了解JSON
JSON简介
JSON:JavaScript Object Notation(JavaScript对象表示法) 轻量级的文本数据交换格式。
JSON语法规则:JSON对象是以键值对的形式保存{"键":"值"} 表示数组方式为[{JSON对象},{JSON对象}]
例:对象 {"ename":"Jack","age":"25"}
数组 [{"ename":"Jack","age":"25"},{"ename":"Lucy","age":"24"}]
JSON与JavaScript交互
- **将字符串转换为JSON对象 **
JSON.parse()
demo1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>字符串转JSON</title>
<script type="text/javascript">
var str = "{\"name\":\"张三\"}";
var json = JSON.parse(str);
console.log(str);
console.log(json);
document.write("姓名:" + json.name);//姓名:张三
</script>
</head>
<body>
</body>
</html>
- 将JSON对象转换为字符串
JSON.stringify()
demo2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON转字符串</title>
<script type="text/javascript">
var json1 = {"name" : "张三"};
var str= JSON.stringify(json1);
document.write(str);//{"name":"张三"}
</script>
</head>
<body>
</body>
</html>
JSON与Java交互
FastJSON解析器
FastJSON jar包下载:https://repo1.maven.org/maven2/com/alibaba/fastjson/1.2.53/fastjson-1.2.53.jar
Student.java
package JSON;
public class Student {
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
FastJSON序列化
把JavaBean对象转成JSON格式的字符串 JSON.toJSONString(Object)
JSONdemo1.java
package JSON;
import com.alibaba.fastjson.JSON;
public class JSONdemo1 {
public static void main(String[] args) {
Student stu = new Student();
stu.setName("张三");
stu.setAge(20);
String s = JSON.toJSONString(stu);
System.out.println(s);//{"age":20,"name":"张三"}
}
}
FastJSON反序列化
把JSON格式的字符串转化为Java Bean对象 JSON.parseArray(list, Object.class)
JSONdemo2.java
package JSON;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
public class JSONdemo2 {
public static void main(String[] args) {
List list=new ArrayList();
list.add(new Student("张三",18));
list.add(new Student("李四",19));
String s = JSON.toJSONString(list);
System.out.println(s);//[{"age":18,"name":"张三"},{"age":19,"name":"李四"}]
List<Student> stu = JSON.parseArray(s, Student.class);
for (Student student : stu) {
System.out.println(student.getName()+":"+student.getAge());
}//张三:18 李四:19
}
}
FastJSON注解
@JSONField(serialize="true/false")
设置serialize值true或false来设置是否下列属性序列化
@JSONField(format="0,000.00")
格式化属性格式