android 使用gson 處理Json

來源:互聯網
上載者:User

標籤:android   style   blog   http   java   color   

Json是一種類似於XML的通用資料交換格式,比XML傳輸效率高.更利於網路傳輸資料。這裡說一些使用Gosn類來處理json資料。Gson比傳統的json處理方式更加快速,Gson開源的。如果有興趣的也可以瞭解一下阿里開發的fastgson,速度也非常快。

 

使用Gosn 處理json非常簡單。第一我們首先建立一個JavaBean類

 

(1)建立User.java

 

public class User {    public User(String name, int age) {        this.name = name;        this.age = age;    }    private String name;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}
View Code

 

 

(2)解析如下json格式資料:

String jsonData = "[{\"name\":\"john\",\"age\":18},{\"name\":\"Jason\",\"age\":16}]";//解析類型Type listType = new TypeToken<LinkedList<User>>(){}.getType(); //建立Gson執行個體,Gson gson = new Gson();也行Gson gson = GsonFactory.getGsonInstance();//解析Json資料LinkedList<User> users = gson.fromJson(jsonData, listType); //迭代輸出for (Iterator iterator = users.iterator(); iterator.hasNext();) { User user = (User) iterator.next(); System.out.println(user.getName()); System.out.println(user.getAge()); }

 

(3)把JavaBean利用Gson產生Json資料

 

 List<User> userList=new LinkedList<User>();
User user1
=new User ("張三",20); userList.add(user1);
User user2
=new User ("John",45); userList.add(user2); //建立Gson執行個體 Gson gson=new Gson();//產生Json格式資料 String jsonData=gson.toJson(userList) System.out.println(jsonData);//輸出結果是: [{"name":"張三","age":20},{"name":"John","age":45}]

 

這裡主要用到Gson兩個方法:

1.解析json的方法 fromJson

2.產生json的方法 toJson

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.