Retrofit解析网页Json数据简单实例

本文介绍如何使用Retrofit进行网络请求,并将返回的数据解析为Java对象。通过一个菜谱API的例子,展示了如何设置依赖、定义网络请求接口、创建实体类、实现RecyclerView适配器以及在MainActivity中调用。
摘要由CSDN通过智能技术生成

Retrofit封装了从Web API下载数据,解析成一个普通的java对象(POJO),这里我们一个菜谱的API做简单演示,供大家一起学习思考。API文档网站http://www.tngou.net/doc/cook的菜谱API接口:http://www.tngou.net/api/cook/list

添加依赖

compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.android.support:recyclerview-v7:23.4.0'

网络请求接口

然后每一次使用都需要定义一个接口,用于下载网络数据,注意其中的{category}是为了之后更好的扩展性,我们定义一个未知的子目录,通过参数中指定可以访问固定的子目录

public interface Service {

   @GET("/api/{category}/list")//网址下面的子目录   category表示分类,因为子目录只有一点不一样
    Call<Tngou> getList(@Path("category") String path,
                        @Query("id") int id,@Query("page") int page,@Query("row")int row);
}

布局

1、自定义显示在Recycle日View的item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/iv_item"
        />
    <LinearLayout
        android:orientation="vertical"
        android:layout_gravity="center_vertical"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content">

        <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="title"
        android:textAppearance="@android:style/TextAppearance.Large"
        />
        <TextView
            android:id="@+id/tv_info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="title"
            android:maxLines="2"
            android:ellipsize="end"
            />

    </LinearLayout>
</LinearLayout>

2、主布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="jiang.rxjavaandvolloy.MainActivity">

   <android.support.v7.widget.RecyclerView
       android:id="@+id/rv_mian"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:scrollbars="vertical"/>
</RelativeLayout>

实体Bean

public class Tngou {
//加上注解
    @SerializedName("status")
    private boolean status;
    @SerializedName("total")
    private int total;
    @SerializedName("tngou")
    private List<Cook> list;

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public List<Cook> getList() {
        return list;
    }

    public void setList(List<Cook> list) {
        this.list = list;
    }
}
public class Cook {
    @SerializedName("id")
    private int id;
    @SerializedName("name")
    private String name;//名称
    @SerializedName("food")
    private String food;//食物
    @SerializedName("img")
    private String img;//图片
    @SerializedName("images")
    private String images;//图片,
    @SerializedName("description")
    private String description;//描述
    @SerializedName("keywords")
    private String keywords;//关键字
    @SerializedName("message")
    private String message;//资讯内容
    @SerializedName("count")
    private int count;//访问次数
    @SerializedName("fcount")
    private int fcount;//收藏数
    @SerializedName("rcount")
    private int rcount;//评论读数

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFood() {
        return food;
    }

    public void setFood(String food) {
        this.food = food;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public String getImages() {
        return images;
    }

    public void setImages(String images) {
        this.images = images;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getKeywords() {
        return keywords;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getFcount() {
        return fcount;
    }

    public void setFcount(int fcount) {
        this.fcount = fcount;
    }

    public int getRcount() {
        return rcount;
    }

    public void setRcount(int rcount) {
        this.rcount = rcount;
    }
}

RecyclerView适配器

public class MyRvAdapter extends RecyclerView.Adapter<MyRvAdapter.MyViewHolder> {
    private Context context;
    private List<Cook> list;

    public MyRvAdapter(Context context, List<Cook> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext())
        .inflate(R.layout.item_content,parent,false));
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Cook cook=list.get(position);
        holder.tvTitle.setText(cook.getName());
        holder.tvInfo.setText(cook.getDescription());
        Glide.with(context)
                .load("http://tnfs.tngou.net/img"+cook.getImg())
                .into(holder.ivImg);
    }

    @Override
    public int getItemCount() {
        if(list!=null)
        {
            return list.size();
        }
        return 0;

    }

    class MyViewHolder extends RecyclerView.ViewHolder{
        ImageView ivImg;
        TextView tvTitle;
        TextView tvInfo;

         public MyViewHolder(View itemView) {
             super(itemView);
             ivImg= (ImageView) itemView.findViewById(R.id.iv_item);
             tvTitle= (TextView) itemView.findViewById(R.id.tv_title);
             tvInfo= (TextView) itemView.findViewById(R.id.tv_info);
         }
     }
}

MainActivity

public class MainActivity extends AppCompatActivity implements Callback<Tngou> {

    private RecyclerView rv;
    private MyRvAdapter myRvAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Retrofit retrofit=new Retrofit.Builder().baseUrl("http://www.tngou.net")
                .addConverterFactory(GsonConverterFactory.create()).build();
        Service service=retrofit.create(Service.class);
        Call<Tngou> call=service.getList("cook",11,11,120);
        call.enqueue(this);
        rv= (RecyclerView) findViewById(R.id.rv_mian);
        LinearLayoutManager lr=new LinearLayoutManager(this);



        lr.setOrientation(OrientationHelper.VERTICAL);
        rv.setLayoutManager(lr);
        rv.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    public void onResponse(Call<Tngou> call, Response<Tngou> response) {
        List<Cook>  list=response.body().getList();
        myRvAdapter=new MyRvAdapter(this,list);
        rv.setAdapter(myRvAdapter);

        LinearLayoutManager layoutManager = (LinearLayoutManager) rv.getLayoutManager();
        //屏幕中最后一个可见子项的position
//        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
//        //当前屏幕所看到的子项个数
//        int visibleItemCount = layoutManager.getChildCount();
//        //当前RecyclerView的所有子项个数
//        int totalItemCount = layoutManager.getItemCount();
//        int state = rv.getScrollState();
//        if(visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 && state == rv.SCROLL_STATE_IDLE){
//            myRvAdapter.notifyDataSetChanged();
//        }
    }

    @Override
    public void onFailure(Call<Tngou> call, Throwable t) {

    }
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值