将Retrofit2与SimpleXmlConverterFactory一起使用
我的问题是多个内联(我相信?)错误响应中的错误错误。
我一直将this link from Simple XML Serialization称为我的信息来源。
我正在处理以下回复:
<?xml version="1.0" encoding="utf-8"?>
<Errors>
<Error>
<Code>1</Code>
<Info>This is why</Info>
</Error>
<Error>
<Code>2</Code>
<Info>This is why</Info>
</Error>
</Errors>
我当前的java对象是ErrorResponse.java:
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import java.util.List;
@Root(name="Errors")
public class ErrorResponse {
@ElementList(name="Error", inline = true)
List<Error> errors;
public ErrorResponse() {
// no arg constructor
}
public void setErrors(List<Error> errors) {
this.errors = errors;
}
public List<Error> getErrors() {
return this.errors;
}
}
和Error.java:
import org.simpleframework.xml.Element;
public class Error {
@Element(name="Code")
int code;
@Element(name="Info")
String info;
public Error() {
// no arg constructor
}
public void setCode(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
public void setInfo(String info) {
this.info = info;
}
public String getInfo() {
return this.info;
}
}
尝试解析响应的errorBody时得到的错误是:
java.lang.RuntimeException:
org.simpleframework.xml.core.ElementException:
Element 'Error' does not have a match in class com.my.package.ErrorResponse at line 1
如果只有1个错误项,我将ErrorResponse类更改为:
..
@Root
public class ErrorResponse {
@Element(name="Error")
Error error;
...
...
然后一切正常,花花公子。当出现多个错误时会出现问题。任何有助于正确解析此XML的帮助或建议都会很棒。我使用以下代码进行errorBody解析响应:
Converter<ResponseBody, ErrorResponse> converter = mRetrofit.responseBodyConverter(ErrorResponse.class, new Annotation[0]);
try {
ErrorResponse errorResponse = converter.convert(response.errorBody());
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:1)
</Info>
,标记需要在您的示例XML ErrorResponse
需要Errors
的名称才能匹配XML @ElementList
不需要在inline
ErrorItem
需要@Root(name = "Error")
以下是ErrorResponse
的代码:
@Root(name = "Errors")
public class ErrorResponse {
@ElementList(inline = true)
List<Error> errors;
public ErrorResponse() {
// no arg constructor
}
public void setErrors(List<Error> errors) {
this.errors = errors;
}
public List<Error> getErrors() {
return this.errors;
}
}
Error
:
@Root(name = "Error")
public class Error {
@Element(name = "Code")
int code;
@Element(name = "Info")
String info;
public Error() {
// no arg constructor
}
public void setCode(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
public void setInfo(String info) {
this.info = info;
}
public String getInfo() {
return this.info;
}
}
修复了示例XML:
<?xml version="1.0" encoding="utf-8"?>
<Errors>
<Error>
<Code>1</Code>
<Info>This is why</Info>
</Error>
<Error>
<Code>2</Code>
<Info>This is why</Info>
</Error>
</Errors>