gpt4 book ai didi

android - 如何从android中的retrofit 2和rxjava获取xml数据

转载 作者:太空狗 更新时间:2023-10-29 13:53:43 26 4
gpt4 key购买 nike

我正在尝试从 xml url 获取数据并遇到一些问题。示例 xml:

<company xmlns="http://www.test.com/test">
<person>
<pId>a11</pId>
<name>Mike</name>
<age>25</age>
<weight>82.7</weight>
<profile>www.test.com/mike.jpb</profile>
<person>
<person>
<pId>a11</pId>
<name>Mike</name>
<age>25</age>
<weight>82.7</weight>
<profile>www.test.com/mike.jpb</profile>
<person>
<person>
<pId>a11</pId>
<name>Mike</name>
<age>25</age>
<weight>82.7</weight>
<profile>www.test.com/mike.jpb</profile>
<person>
</company>

我在 java 代码中做了什么:

Observable<List<Person>> call = APIClient.getRetrofitAPIClient().getPerson(APIClient.API_PARAMETER);
subscription = call
.subscribeOn(Schedulers.io()) // optional if you do not wish to override the default behavior
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Person>>() {
@Override
public void onCompleted() {

}

@Override
public void onError(Throwable e) {
if (e instanceof HttpException) {
HttpException response = (HttpException)e;
int code = response.code();
Log.e("TOTAL", "code "+code);
}
}

@Override
public void onNext(List<Person> p) {
showResults(p);
}
});

现在

public interface APIService {

@GET("/{paramter}")
rx.Observable<List<Person>> getPersons(@Path("paramter") String paramter);
}

// get retrofit api services
public static APIService getRetrofitAPIClient(){
if(apiService == null){
Retrofit retrofit =new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.client(okHttpClient)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
apiService = retrofit.create(APIService.class);
}
return apiService;
}

模型类

@Root(name = "person")
public class Person {
@Element(name = "pId")
private String pId;

@Element(name = "name")
private String name;

@Element(name = "age")
private int age;

@Element(name="weight")
private double weight;

@Element(name="profile")
private String profile;
}

@Root(name = "company")
public class Company {
@ElementList(entry = "person", inline = true)
private List<Person> companies;
}

我在 logcat 中得到关注:

java.lang.RuntimeException: Unable to start activity ComponentInfo{co.test/co.test.activity.MainActivity}: java.lang.IllegalArgumentException: Unable to create converter for java.util.List for method APIService.getPerson

提前致谢。

最佳答案

SimpleXmlConverterFactory不支持List,需要将API接口(interface)result定义为Person数组:

public interface APIService {

@GET("/{paramter}")
rx.Observable<Person[]> getPersons(@Path("paramter") String paramter);
}

参见 SimpleXmlConverterFactory 类 documentation :

This converter only applies for class types. Parameterized types (e.g., {@code List}) are * not handled.

关于android - 如何从android中的retrofit 2和rxjava获取xml数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42104191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com