一.导入volley的依赖或jar包
二.仿照StringRequest写一个自定义的请求对象,这样可以把json解析成需要的javabean
1.定义一个类继承request
public class MyRequest<T> extends Request<T> {
private static final String TAG = "MyRequest";
//需要解析的json字符串的泛型
private Class<T> mClass;
//解析成功后的接口对象,用于数据的回调
private Response.Listener<T> mSuccessListener;
public MyRequest(String url, Class<T> clazz, Response.ErrorListener listener,Response.Listener<T> successListener) {
super(url, listener);
//通过构造函数,传入需要的字段
this.mClass=clazz;
this.mSuccessListener=successListener;
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
Gson gson =new Gson();
//根据gson解析,把从网络获取的字节数据解析成javabean
T t = gson.fromJson(new String(response.data), mClass);
return Response.success(t, HttpHeaderParser.parseCacheHeaders(response));
}
//数据的回调
@Override
protected void deliverResponse(T t) {
mSuccessListener.onResponse(t);
}
}
二.javaBean
<pre name="code" class="java">public class JavaBean {
private static final String TAG = "JavaBean";
public int retcode;
public List<DataBean> data;
public List<Integer> extend;
public static class DataBean {
public int id;
public String title;
public int type;
public List<ChildrenBean> children;
public static class ChildrenBean {
public int id;
public String title;
public int type;
public String url;
}
}
}
三.请求数据代码
public class MainActivity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<JavaBean> {
public static final String HOST = "http://192.168.56.1:8080/zhbj/categories.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/*volley请求三部曲
一.创建请求对象(解析数据成功或失败通过接口回调)
二.创建请求队列
三,添加请求到队列,发起请求
*
* */
public void request(View view){
//创建请求对象
MyRequest<JavaBean> request=new MyRequest<>(HOST,JavaBean.class,this,this);
//创建请求队列
RequestQueue queue = Volley.newRequestQueue(this);
//添加请求
queue.add(request);
}
@Override
public void onErrorResponse(VolleyError volleyError) {
}
@Override
public void onResponse(JavaBean javaBean) {
List<JavaBean.DataBean> data = javaBean.data;
Toast.makeText(this,data.size()+"个数" , Toast.LENGTH_SHORT).show();
}
}