一、JS中字符串与JSON的互相转换
在JS当中字符串转换成JSON常常会用到以下来表明
二、FastJSON对象序列化和反序列化
1、FastJson是阿里巴巴的开源JSON解析库,它可以解析 JSON 格式的字符串,也是国人常常使用的一种解析json格式的方式
在使用 FastJSON前,我们先需要下载FastJson而下载fastJson我们需要进入以下进行搜索FastJson进行下载FastJson相关的jar包
https://github.com/https://github.com/然后把包导入我们的工程当中
2、FastJson的使用
FastJson的序列化与反序列化的使用
例如我们定义了一个Student的类为以下拥有相关的get和set方法
public class Student {
private String name;//姓名
private String sex;//性别
private String sno;//学号
private Date entryDate;//入学时间
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getEntryDate() {
return entryDate;
}
public void setEntryDate(Date entryDate) {
this.entryDate = entryDate;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
}
对于相关相关序列化为以下
public static void main(String[] args) {
Student student=new Student();
student.setName("小明");
student.setSex("男");
student.setSno("1001");
//通过Calendar来获取时间使得更好的导入进student
Calendar entryDate=Calendar.getInstance();
entryDate.set(2021, 11, 12, 17, 40, 0);
//获取当前的时间是从1970年到输入日期的毫秒数
student.setEntryDate(entryDate.getTime());
//把student对象序列化为JSON数据的字符串
String json=JSON.toJSonString(entryDate);
//把JSON数据序列化为student对象为以下
Student student2=JSON.parseObject(json,Student.class);
}
当然,对于其中的entryDate得到的是毫秒数我们应该如下来把它转换成我们所需要的
在FastJSON中提供给了我们相关的转换方式,于是我们可以如下使用
//当我们不想显示相关的学号的话,我们可以如下 @JSonField(serialize=false) private String sno;//学号 @JSonField(name="入学时间",format="yyyy年MM月dd日") private Date entryDate;//入学时间
对于如果是对象数组的话,我们可以如下
public static void main(String[] args) {
List StudentList=new ArrayList();
for(int i=1;i<=100;i++) {
Student student=new Student();
student.setSex("男");
student.setSno("1001"+i);
StudentList.add(student);
}
String json=JSON.toJSonString(StudentList);
System.out.println(json);
List student2=JSON.parseArray(json,Student.class);
for(Student e:student2) {
System.out.println(e.getSno()+":"+e.getSex());
}
}
以上就是json的总结



