相關(guān)依賴
添加Retrofit 及xml解析的依賴
implementation 'com.squareup.retrofit2:retrofit:(insert latest version)'
implementation ('com.squareup.retrofit2:converter-simplexml:2.1.0'){
exclude group: 'xpp3', module: 'xpp3'
exclude group: 'stax', module: 'stax-api'
exclude group: 'stax', module: 'stax'
}
也可以通過https://square.github.io/retrofit/#download下載Retrofit最新的jar包
編寫解析的實(shí)體類XMLService 其中包含有單個(gè)屬性如:type question等,也包含一個(gè)鏈表relatedQuestions使用@ElementList標(biāo)識(shí),并且由于不支持內(nèi)部類則重新編寫另一個(gè)RelatedQuestion的實(shí)體類
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import java.util.List;
/**
* Root:修飾實(shí)體類厘托,根節(jié)點(diǎn)近范,最外層的節(jié)點(diǎn),
* name:節(jié)點(diǎn)的名稱
* strict:xml中有的元素集峦,而實(shí)體類中沒有伏社,在實(shí)體類的@(Root)中加上strict = false
*
* Element:單個(gè)節(jié)點(diǎn)非 實(shí)體/鏈表
* name:節(jié)點(diǎn)名稱
*
* ElementList:標(biāo)記鏈表
* inline:ElementList的一個(gè)屬性,由于ElementList包了一層塔淤,如果為false將不能解析
* required : 實(shí)體類中有摘昌,xml中沒有,且聲明為@Element的高蜂,在@Element中加上required = false
*/
@Root(name = "Response", strict = false) //name:要解析的xml數(shù)據(jù)的頭部
public class XMLService {
@Element(name = "Type")
public int type;
@Element(name = "Question")
public String question;
@Element(name = "Content")
public String content;
@Element(name = "Similarity")
public double similarity;
@ElementList(required = false, inline = true,name = "RelatedQuestions")
public List<RelatedQuestion> relatedQuestions;
@Override
public String toString() {
return "CcbBlpResponse{" +
"type=" + type +
", question='" + question + '\'' +
", content='" + content + '\'' +
", similarity=" + similarity +
", relatedQuestions=" + relatedQuestions.get(0).question +
'}';
}
}
RelatedQuestion實(shí)體類
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
* Root:修飾實(shí)體類聪黎,根節(jié)點(diǎn),最外層的節(jié)點(diǎn)备恤,
* name:節(jié)點(diǎn)的名稱
* strict:xml中有的元素稿饰,而實(shí)體類中沒有,在實(shí)體類的@(Root)中加上strict = false
*
* required: 因?yàn)閤ml返回可能不含有Question 所以required = false
*/
@Root(name = "RelatedQuestions", strict = false)
class RelatedQuestion {
@Element(name = "Question",required = false)
String question;
}
初始化Retrofi及Service
Retrofi初始胡網(wǎng)上一大把露泊,直接添加xml解析器即可:
.addConverterFactory(SimpleXmlConverterFactory.create()) // 添加xml轉(zhuǎn)換器
Service
/**
* ccb nlp
*
* @return
*/
@GET("robot-bankccb/ask-robot.action?")
Flowable<XMLService> ccbNlpRequest(@Query("userId") String userId,
@Query("sessionId") String sessionId,
@Query("dstType") String dstType,
@Query("playform") String playform,
@Query("question") String question);
到此解析基本完成喉镰,唯一遇到的問題就是當(dāng)有些參數(shù)返回時(shí)空的時(shí)候需要特殊處理如RelatedQuestion的question有時(shí)會(huì)返回未空,所以增加required = false惭笑;