Retrofit Xml解析

2019-08-27  本文已影响0人  提丶米

相关依赖

添加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包

编写解析的实体类XMLService 其中包含有单个属性如:type question等,也包含一个链表relatedQuestions使用@ElementList标识,并且由于不支持内部类则重新编写另一个RelatedQuestion的实体类


import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

import java.util.List;

/**
 *     Root:修饰实体类,根节点,最外层的节点,
 *     name:节点的名称
 *   strict:xml中有的元素,而实体类中没有,在实体类的@(Root)中加上strict = false
 *
 *  Element:单个节点非 实体/链表
 *     name:节点名称
 *
 * ElementList:标记链表
 *      inline:ElementList的一个属性,由于ElementList包了一层,如果为false将不能解析
 *   required : 实体类中有,xml中没有,且声明为@Element的,在@Element中加上required = false
 */
@Root(name = "Response", strict = false) //name:要解析的xml数据的头部
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实体类

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
 *     Root:修饰实体类,根节点,最外层的节点,
 *     name:节点的名称
 *   strict:xml中有的元素,而实体类中没有,在实体类的@(Root)中加上strict = false
 *
 *   required: 因为xml返回可能不含有Question 所以required = false
 */
@Root(name = "RelatedQuestions", strict = false)
class RelatedQuestion {
    @Element(name = "Question",required = false)
    String question;
}

初始化Retrofi及Service

Retrofi初始胡网上一大把,直接添加xml解析器即可:

 .addConverterFactory(SimpleXmlConverterFactory.create()) // 添加xml转换器
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);

到此解析基本完成,唯一遇到的问题就是当有些参数返回时空的时候需要特殊处理如RelatedQuestion的question有时会返回未空,所以增加required = false;

上一篇 下一篇

猜你喜欢

热点阅读