XStream的使用方法、簡單使用方法、xml的解析方法


下面介紹的是在Android Studio中的使用

Android Studio中目前支持的Xstream最高版本是xstream-1.4.7.jar,大家可以在網上下載,我的是在開源中國項目中有這個jar包,我是直接將jar包放到libs中使用的,因為我嘗試在build.gradle中通過complie的方法添加依賴,但是編譯的時候還是不通過。

我使用的是okhttp的client。

下面介紹的是項目開發中從網絡獲取xml文件並解析成javaBean的方法。

1.網絡服務器中的xml文件

<person name="johnson">
<firstname>Joe</firstname>
<lastname>Walnes</lastname> <phone> <phoneno>0107654321</phoneno> </phone> <phone> <phoneno>13800008888</phoneno> </phone> </person>

 

2.     javaBean

/**
 * Created by weizh_000 on 2016/8/16.
 */

//設置Person類在xml中的別名
@XStreamAlias("person")
public class Person {
    //將name設置為XML person字段的 attribute
    @XStreamAsAttribute()
    private String firstname;
    private String lastname;
    //該變量不是xml中的一個字段,應去掉
    @XStreamImplicit()
    private List<Phone> phone = new ArrayList<Phone>();
    @Override
    public String toString() {
        return "Person{" +
                "firstname='" + firstname + '\'' +
                ", lastname='" + lastname + '\'' +
                '}';
    }

    public List<Phone> getPhoneno() {
        return phone;
    }

    public void setPhoneno(List<Phone> phone) {
        this.phone = phone;
    }

    class Phone{
        String phoneno;

        @Override
        public String toString() {
            return "Phone{" +
                    "phoneno=" + phoneno +
                    '}';
        }
    }
}

 

3.使用

public void test() {
        OkHttpClient okHttpClient = new OkHttpClient();//定義client
        Request request = new Request.Builder().url("http://192.168.1.100:8080/test/test.xml").build();//定義request
        okhttp3.Call call = okHttpClient.newCall(request);//用client使用call
        call.enqueue(new okhttp3.Callback() {//異步請求網絡數據
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {//請求失敗的情況
                System.out.println("fail:");
                e.printStackTrace();
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {//請求成功的情況
                XStream xStream = new XStream(new DomDriver("UTF-8"));
          //對指定的類使用Annotations 進行序列化,這步非常關鍵
                xStream.processAnnotations(Person.class);
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    Person person = (Person) xStream.fromXML(string);
                    System.out.println(person.toString()); 
                    System.out.println(person.getPhoneno().toString()); 
               }
           }
      });
}

其實也就這步關鍵而已,其他的不重要:

  //對指定的類使用Annotations 進行序列化
   xstream.processAnnotations(Person.class);

 

運行結果:

Person{firstname='Joe', lastname='Walnes'}
[Phone{phoneno=0107654321}, Phone{phoneno=13800008888}]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM