SpringBoot實(shí)現(xiàn)子類(lèi)的反序列化示例代碼
目標(biāo)
在SpringBoot接口中,我們一般用@RequestBody類(lèi)注解需要反序列化的對(duì)象,但是當(dāng)存在多個(gè)子類(lèi)的情況下,常規(guī)的反序列化不能滿(mǎn)足需求,比如:
我們有一個(gè)類(lèi)Exam用于表示一張?jiān)嚲恚?/p>
@Data public class Exam { private String name; private List<Question> questions; }
這里Question比較特殊,Question本身是一個(gè)抽象類(lèi),提供了一些通用的方法調(diào)用,實(shí)際子類(lèi)有單選題、多選題、判斷題多種情況
實(shí)現(xiàn)
SprintBoot內(nèi)置的序列化是使用的Jackson,查閱文檔后發(fā)現(xiàn)Jackson提供了@JsonTypeInfo和@JsonSubTypes這兩個(gè)注解,搭配使用,可以根據(jù)指定的字段值來(lái)指定實(shí)例化中用到的具體的子類(lèi)類(lèi)型
這幾個(gè)類(lèi)的實(shí)際代碼如下:
抽象基類(lèi)Question:
@Data @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", visible = true) @JsonSubTypes({ @JsonSubTypes.Type(value = SingleChoiceQuestion.class, name = Question.SINGLE_CHOICE), @JsonSubTypes.Type(value = MultipleChoiceQuestion.class, name = Question.MULTIPLE_CHOICE), @JsonSubTypes.Type(value = TrueOrFalseQuestion.class, name = Question.TRUE_OR_FALSE), }) public abstract class Question { protected static final String SINGLE_CHOICE = "single_choice"; protected static final String MULTIPLE_CHOICE = "multiple_choice"; protected static final String TRUE_OR_FALSE = "true_or_false"; protected String type; protected String content; protected String answer; protected boolean isCorrect(String answer) { return this.answer.equals(answer); } }
判斷題TrueOrFalseQuestion:
@Data @EqualsAndHashCode(callSuper = true) public class TrueOrFalseQuestion extends Question { public TrueOrFalseQuestion() { this.type = TRUE_OR_FALSE; } }
選擇題ChoiceQuestion:
@Data @EqualsAndHashCode(callSuper = true) public abstract class ChoiceQuestion extends Question { private List<Option> options; @Data public static class Option { private String code; private String content; } }
單選題SingleChoiceQuestion:
@Data @EqualsAndHashCode(callSuper = true) public class SingleChoiceQuestion extends ChoiceQuestion { public SingleChoiceQuestion() { this.type = SINGLE_CHOICE; } }
多選題MultipleChoiceQuestion:
@Data @EqualsAndHashCode(callSuper = true) public class MultipleChoiceQuestion extends ChoiceQuestion { public MultipleChoiceQuestion() { this.type = MULTIPLE_CHOICE; } @Override public void setAnswer(String answer) { this.answer = sortString(answer); } @Override public boolean isCorrect(String answer) { return this.answer.equals(sortString(answer)); } private String sortString(String str) { char[] chars = str.toCharArray(); Arrays.sort(chars); return String.valueOf(chars); } }
測(cè)試
接下來(lái)測(cè)試一下
定義一個(gè)接口,我們可以使用@RequestBody傳入一個(gè)Exam對(duì)象,返回解析結(jié)果:
@RequestMapping(value = "/exam", method = RequestMethod.POST) public List<String> parseExam(@RequestBody Exam exam) { List<String> results = new ArrayList<>(); results.add(String.format("Parsed an exam, name = %s", exam.getName())); results.add(String.format("Exam has %s questions", exam.getQuestions().size())) List<String> types = new ArrayList<>(); for (Question question : exam.getQuestions()) { types.add(question.getType()); } results.add(String.format("Questions types: %s", types.toString())); return results; }
項(xiàng)目跑起來(lái),調(diào)用接口測(cè)試一下:
curl -X POST \ http://127.0.0.1:8080/exam/ \ -H 'Content-Type: application/json' \ -d '{ "name":"一場(chǎng)考試", "questions": [ { "type": "single_choice", "content": "單選題", "options": [ { "code":"A", "content": "選項(xiàng)A" },{ "code":"B", "content": "選項(xiàng)B" }], "answer": "A" },{ "type": "multiple_choice", "content": "多選題", "options": [ { "code":"A", "content": "選項(xiàng)A" },{ "code":"B", "content": "選項(xiàng)B" }], "answer": "AB" },{ "type": "true_or_false", "content": "判斷題", "answer": "True" }] }'
接口返回如下:
[ "Parsed an exam, name = 一場(chǎng)考試", "Exam has 3 questions", "Questions types: [single_choice, multiple_choice, true_or_false]" ]
這里不同類(lèi)型的question,type字段都能正確讀取,表明反序列化過(guò)程中確實(shí)是調(diào)用了具體子類(lèi)對(duì)應(yīng)的類(lèi)來(lái)進(jìn)行實(shí)例化的。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Java8如何將Array轉(zhuǎn)換為Stream的實(shí)現(xiàn)代碼
這篇文章主要介紹了Java8如何將Array轉(zhuǎn)換為Stream的實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09關(guān)于mybatis傳入?yún)?shù)一直為null的問(wèn)題
這篇文章主要介紹了關(guān)于mybatis傳入?yún)?shù)一直為null的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07spring boot org.junit.jupiter.api不存在的解決
這篇文章主要介紹了spring boot org.junit.jupiter.api不存在的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09spring 整合mybatis后用不上session緩存的原因分析
因?yàn)橐恢庇胹pring整合了mybatis,所以很少用到mybatis的session緩存。什么原因呢?下面小編給大家介紹spring 整合mybatis后用不上session緩存的原因分析,需要的朋友可以參考下2017-02-02java題解Leetcode 8字符串轉(zhuǎn)換整數(shù)
這篇文章主要為大家介紹了java題解Leetcode 8字符串轉(zhuǎn)換整數(shù)實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06詳解springcloud 基于feign的服務(wù)接口的統(tǒng)一hystrix降級(jí)處理
這篇文章主要介紹了詳解springcloud 基于feign的服務(wù)接口的統(tǒng)一hystrix降級(jí)處理,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-06-06