您的位置:首页 > Web前端 > JavaScript

fastjson用法1

2015-07-23 13:00 633 查看
整理了一下fastjson的一些用法,这里选用了1.2.4版本

//学生类
public class Student {
private Integer studentId;
private String name;
private int age;
private Date birth;
}


//课程类
public class Course {
private Integer courseId;
private String courseName;
}


//分数类
public class Score {
private Student student;
private Course course;
private double score;
}




省略了get和set方法,无参、有参构造方法,以及toString()方法


public class JSONDemo01 {

public static void main(String[] args) {

Student student = new Student(1, "张三", 15, new Date());
Course course = new Course(1, "语文");
Score score = new Score(student, course, 90.50);

// 把自定义的JAVA对象转化为JSON字符串
String jsonString = JSON.toJSONString(score);
System.out.println(jsonString);
// 默认输出格式:对象属性按照字母排序,时间转换为毫秒数,字符串用双引号包含
// {"course":{"courseId":1,"courseName":"语文"},"score":90.5,"student":{"age":15,"birth":1437628296881,"name":"张三","studentId":1}}

// 把JSON字符串转化为自定义的JAVA对象
Score score2 = JSON.parseObject(jsonString, Score.class);
System.out.println(score2 + "\n" + score2.equals(score));
// 自定义类型的toString()方法输出结果为Score [student=Student [studentId=1, name=张三, age=15, birth=Thu Jul 23 15:20:52 CST 2015], course=Course
// [courseId=1, courseName=语文], score=90.0]
// Object类的equals方法输出结果为false
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  fastjson JSON