From ed167fe5cc16f9b6a1f9e85206525bcea99cf0f8 Mon Sep 17 00:00:00 2001 From: zhengsongjun Date: Mon, 20 Dec 2021 12:25:02 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=8C=E6=88=90=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E5=8C=96=E5=8F=8D=E5=BA=8F=E5=88=97=E5=8C=96=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 5 ++++ .../com/github/hcsp/encapsulation/Main.java | 12 ++++++---- .../github/hcsp/encapsulation/Student.java | 24 +++++++++++++++++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index c20b489..825a533 100644 --- a/pom.xml +++ b/pom.xml @@ -70,6 +70,11 @@ 5.6.0 test + + com.alibaba + fastjson + 1.2.79 + diff --git a/src/main/java/com/github/hcsp/encapsulation/Main.java b/src/main/java/com/github/hcsp/encapsulation/Main.java index 51ce4a1..14597ac 100644 --- a/src/main/java/com/github/hcsp/encapsulation/Main.java +++ b/src/main/java/com/github/hcsp/encapsulation/Main.java @@ -1,5 +1,7 @@ package com.github.hcsp.encapsulation; +import com.alibaba.fastjson.JSON; + public class Main { /* 假设你正在为学校开发一个学生分数记录系统 @@ -20,13 +22,15 @@ public static void main(String[] args) { student.setScore(60); student.setRetakingExam(true); String json = serialize(student); - System.out.println(json); - student = deserialize(json); } // 序列化:将Student类转换成JSON字符串 - public static String serialize(Student student) {} + public static String serialize(Student student) { + return JSON.toJSONString(student); + } // 反序列化:将JSON字符串转换成Student对象 - public static Student deserialize(String json) {} + public static Student deserialize(String json) { + return JSON.parseObject(json,Student.class); + } } diff --git a/src/main/java/com/github/hcsp/encapsulation/Student.java b/src/main/java/com/github/hcsp/encapsulation/Student.java index 85d2f55..8ee3f34 100644 --- a/src/main/java/com/github/hcsp/encapsulation/Student.java +++ b/src/main/java/com/github/hcsp/encapsulation/Student.java @@ -10,4 +10,28 @@ public class Student { /** 分数 */ private int score; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isRetakingExam() { + return retakingExam; + } + + public void setRetakingExam(boolean retakingExam) { + this.retakingExam = retakingExam; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } }