簡體   English   中英

使用SimpleXmlConverter或任何其他庫將自定義模型轉換為XML字符串?

[英]Convert custom model to XML string with SimpleXmlConverter or by any other library?

我正在使用Retrofit2和SimpleXmlConverter來調用API。 請求和響應基於XML數據。 我需要在請求正文中發送帶有標簽的XML字符串。

通過使用SimpleXmlConverter,我可以輕松地將XML響應解析為自定義模型,但是無法像使用JsonConverters一樣將自定義模型轉換為XML字符串。

有什么方法可以將我的自定義模型轉換為XML字符串?

通過使用SimpleXmlConverter庫的Serializer類,可以進行解析。 請參考以下代碼:

這是自定義模型類

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

@Root(name = "notification", strict = false)
public class NotificationModel {

    @Element(name = "code")
    public String errorCode;

    @Element(name = "message")
    public String errorMessage;
}

這是您要解析到模型中的xml字符串

<notification xmlns:d="http://www.website.com/pref/data">
    <code>004</code>
    <message>Error during value update</message>
    <severity>info</severity>
    <target />
</notification>

使用下面的代碼來解析上面的xml字符串

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

String xmlString = "above xml string"
try {
    Serializer serializer = new Persister();
    NotificationModel notificationModel = serializer.read(NotificationModel.class, xmlString);
    //TODO: Use notificationModel's variables with filled values
} catch (Exception e) {
    e.printStackTrace();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM