xutils获取json并解析

这篇文章主要是利用xutils从服务器获取数据,并用gson解析到本地,显示出来。
xutils获取json并解析_第1张图片

1、 xutils从服务器获取数据原理:

使用方法:

  HttpUtils http=new HttpUtils;
        http.send(HttpRequest.HttpMethod.GET,"url", new RequestCallBack() {
            @Override
            public void onSuccess(ResponseInfo responseInfo) {

            }
            @Override
            public void onFailure(HttpException e, String s) {

            }
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
            }
        });

1、 发送的参数列表 http.send(HttpRequest.HttpMethod.GET,”url”, new RequestCallBack()。
http.send源代码:

public <T> HttpHandler<T> send(HttpMethod method, String url, RequestCallBack<T> callBack) { return this.send(method, url, (RequestParams)null, callBack); }

看HttpHnadler类可知,发送的请求最终是在httphandler中的doInBackground,也就是开启任务,发送请求给服务器,使用ResponseInfo类接收从网络获取数据。

 protected Void doInBackground(Object... params) {

2 、 RequestCallBack()源代码如下:抽象类RequestCallBack中的两个抽象方法,分别是成功和失败的回调。成功接收的参数即是从服务器获取的数据ResponseInfo,失败后传入的参数为异常类,打印异常信息。

public abstract class RequestCallBack<T> {
    private static final int DEFAULT_RATE = 1000;
    private static final int MIN_RATE = 200;
    private String requestUrl;
    protected Object userTag;
    private int rate;
    public RequestCallBack() {
        this.rate = 1000;
    }
   public RequestCallBack(int rate, Object userTag) {
        this.rate = rate;
        this.userTag = userTag;
    }
    public void setUserTag(Object userTag) {
        this.userTag = userTag;
    }
    public void onStart() {
    }
    public void onCancelled() {
    }
    public void onLoading(long total, long current, boolean isUploading) {
    }
    public abstract void onSuccess(ResponseInfo<T> var1);
    public abstract void onFailure(HttpException var1, String var2);
}

2、 gson : 使用gson要定义bean类,并且类中定义的名称要和json解析数据的名称相同。

Demo中代码如下:
MainActivity中的代码:

public class MainActivity extends Activity {
    //获取天气的url:http://m.weather.com.cn/atad/101010100.html
    private String url = "https://api.douban.com/v2/book/1220562";
    private TextView tv_tag;
    private ListView listview;
    private MyAdapter adapter;
    private ArrayList<Tag> list;
    private TextView tv_title;
    private TextView tv_price;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // tv_tag=(TextView) findViewById(R.id.tv_tag);
        listview = (ListView) findViewById(R.id.listview);
        tv_title=(TextView) findViewById(R.id.tv_title);
        tv_price=(TextView) findViewById(R.id.tv_price);
        list = new ArrayList<Tag>();
        //初始化数据;
        getData();
        adapter = new MyAdapter(this, list);
        listview.setAdapter(adapter);
    }
    private void getData() {
        // TODO Auto-generated method stub
        HttpUtils http=new HttpUtils();
        http.send(HttpMethod.GET, url, new RequestCallBack<String>() {
           //加载失败的时候;
            @Override
            public void onFailure(HttpException e, String s) {
                // TODO Auto-generated method stub 
            }
           //加载成功;
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                // TODO Auto-generated method stub
                dealData(responseInfo.result);
                System.out.println("---"+responseInfo.result);
            }
            //正在加载的时候显示;可以显示百分比;也可以弹出对话框之类的提示;
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                // TODO Auto-generated method stub
                super.onLoading(total, current, isUploading);
            }
        });
    }
    private void dealData(String result) {
        //gson在解析的时候,{}代码对象;【】代表集合;
        Gson gson = new Gson();
        //json中所有的数据已经返回到book实体中;
        Book book = gson.fromJson(result, Book.class);
        Log.i("info", book.getTitle() + ":" + book.getPublisher() + ":"
                + book.getTags().size());
        tv_title.setText("书名:"+book.getTitle());
        tv_price.setText("价格:"+book.getPrice());
        list = book.getTags();
        //list集合加入数据后刷新adapter;不刷新则获取不到数据;
        adapter.refreshData(list);
    }

}

2在适配器中的代码如下:

public class MyAdapter extends BaseAdapter{
    private ArrayList<Tag> list;
    private Context context;
    public MyAdapter(Context context,ArrayList<Tag> list){
       this.context=context;
       this.list=list;
    }
    //刷新list列表中的adapter;
    public void refreshData(ArrayList<Tag> list) {
           this.list=list;
           notifyDataSetChanged();
        }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();

    }
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        // TODO Auto-generated method stub
        ViewHolder vh;
        if(convertView==null){
            vh=new ViewHolder();
            convertView=LayoutInflater.from(context).inflate(R.layout.item, null);
            vh.tv_count=(TextView) convertView.findViewById(R.id.tv_count);
            vh.tv_title=(TextView) convertView.findViewById(R.id.tv_title);
            convertView.setTag(vh); 
        }else{
            vh=(ViewHolder) convertView.getTag();
        }
    vh.tv_count.setText(list.get(position).getCount());
        vh.tv_title.setText(list.get(position).getTitle());
        return convertView;
    }
    static final class ViewHolder{
        TextView tv_count;
        TextView tv_title;
    }

Demo下载地址eclipse版
http://download.csdn.net/detail/androidxiaogang/9204873

你可能感兴趣的:(json,gson,xutils)