1.Google Json利器之Gson 评价:简单,方便。 2.阿里巴巴 Json利器之FastJson 评价:大数据的性能还是蛮快的。
3.IBM Json利器之Json4J 少人用。
首先导入volley.jar和gson.jar的包;
在主配置文件里面加上internet权限‘
然后就是代码:
mainActivity.java
public class MainActivity extends Activity {
//json数据的来源;豆瓣读书的接口。
private String url = "https://api.douban.com/v2/book/1220562";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getData();
}
private void getData() {
// TODO Auto-generated method stub
StringRequest stringRequest = new StringRequest(url, new Listener<String>() {
@Override
public void onResponse(String arg0) {
Log.i("info", arg0);
dealData(arg0);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
}
});
//使用Volley发送网路请求
new Volley().newRequestQueue(getApplicationContext()).add(stringRequest);
}
protected void dealData(String result) {
//json转化为对象;
Gson gjson = new Gson();
Book book = gjson.fromJson(result,Book.class);
Log.i("info",book.getPublisher()+","+book.getSummary()+","+book.getTitle()+","+book.getTag().size());
}
两个实体类:
Book.java
public class Book {
private String title;
private String publisher;
private String summary;
private ArrayList<Tag> tags;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public ArrayList<Tag> getTag() {
return tags;
}
public void setTag(ArrayList<Tag> tags) {
this.tags = tags;
}
}
Tag.java
public class Tag {
/*
"count": 133,
"name": "片山恭一",
"title": "片山恭一"
*/
private String count;
private String name;
private String title;
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}