02-JSON

nobility 发布于 2021-09-02 394 次阅读


JSON

Java解析JSON需要借助Fastjson或其他第三方json解析,Fastjson是阿里巴巴旗下的开源项目,国内使用较多,需要引入相关jar包,从maven官网中查找Fastjson并下载,导入项目即可

  • 要求JavaBean必须有空构造方法和Setter和Getter方法
  • 解析成字符串时不会对null值进行解析,解析成JavaBean时对于不存在的值会解析成null
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;

import java.util.*;

class Student {
  private Integer ID;
  private String name;
  @JSONField(serialize = false) //serialize设置为false则该属性就不会被解析
  private Boolean sex;
  @JSONField(name = "birthdayDateTime", format = "yyyy-MM-dd HH:mm:ss.SSS")
  //该注解用于约束JSON解析,name代表JSON的key值,默认是属性名,format格式化输出时间
  private Date birthday;
  private String resume;

  public Student() {
  }

  public Student(Integer ID, String name, Boolean sex, Date birthday, String resume) {
    this.ID = ID;
    this.name = name;
    this.sex = sex;
    this.birthday = birthday;
    this.resume = resume;
  }
  /*Setter和Getter一级toString方法省略...*/
}

public class Main {
  public static void main(String[] args) {
    /*单个对象的JSON解析*/
    System.out.println("----------------------------------单个对象解析------------------------------------------");
    Student student = new Student(0, "张三", true, new Date(), null);
    String stringJSON = JSON.toJSONString(student); //不会对null值进行解析
    //{"birthdayDateTime":"2020-12-05 10:55:43.743","iD":0,"name":"张三"}
    System.out.println(stringJSON);
    Student studentParse = JSON.parseObject(stringJSON, Student.class); //对于不存在的值会解析成null
    //Student{ID=0, name='张三', sex=null, birthday=Sat Dec 05 10:55:43 CST 2020, resume='null'}
    System.out.println(studentParse);
    /*对象集合的JSON解析*/
    System.out.println("----------------------------------对象集合解析------------------------------------------");
    List<Student> students = new ArrayList<>();
    students.add(new Student(0, "张三", true, new Date(), null));
    students.add(new Student(1, "李四", false, new Date(), "李四的简历"));
    String stringsJSON = JSON.toJSONString(students); //同样使用toJSONString()方法进行解析
    //[{"birthdayDateTime":"2020-12-05 11:11:26.749","iD":0,"name":"张三"},{"birthdayDateTime":"2020-12-05 11:11:26.749","iD":1,"name":"李四","resume":"李四的简历"}]
    System.out.println(stringsJSON);
    List<Student> studentsParse = JSON.parseArray(stringsJSON, Student.class);  //使用parseArray()方法进行解析
    //[Student{ID=0, name='张三', sex=null, birthday=Sat Dec 05 11:11:26 CST 2020, resume='null'}, Student{ID=1, name='李四', sex=null, birthday=Sat Dec 05 11:11:26 CST 2020, resume='李四的简历'}]
    System.out.println(studentsParse);
  }
}
此作者没有提供个人介绍
最后更新于 2021-09-02