Android 网络请求一般都涉及到图片和JSON数据,怎样快速的请求网络JSON数据,解析JSON数据,并且一步生成自己想要的Java bean实体类?这个涉及到Android 开发效率的问题。由于接触Android 网络这方面比较多,自然就找到一些好的方法来快速开发Android 网络模块的相关内容,接下来就为大家揭晓 一步快速请求,解析JSON 数据生成对应的Java bean实体类的方法。
注:我们先把思路讲解下吧:
1.网络请求JSON数据代码可以自己写,当然我还是推荐使用网络上开源的稳定的框架---Volley,相信很多人应该了解这个开源框架吧,不知道的百度去,这是一个很好用的网络请求开源框架。
2.解析JSON 数据,最好的方法无疑是使用网络上线程的工具 jar包(谷歌的GSON 阿里的FastJson),我这里选择的是阿里的FastJson,FastJson有优势,具体优势后面讲解。
3.解析JSON数据后要将数据保存到 实体类中,我们需要自己定义实体类,但是,在使用FastJson 解析JSON数据的时候必须确保 JSON 数据字段和 实体类的成员变量名字相同,否则FastJson 是解析不出来的(Gson也解析不出来),但是使用FastJson 不区分实体类成员变量的大小写,而Gson 区分,这就是为什么我选择FastJson解析JSON数据了。
一.我们需要解析JSON数据必然需要先定义 JSON数据信息实体类,然后才能解析JSON数据,将数据保存到类中。但是,定义这个类不需要一个变量的去敲代码,而且有可能出错。这里我们拿中国天气预报的一条JSON数据说明,http://www.weather.com.cn/data/cityinfo/101010100.html ,浏览器请求后获得的JSON数据是:
{
"weatherinfo": {
"city": "北京",
"cityid": "101010100",
"temp1": "5℃",
"temp2": "-3℃",
"weather": "晴",
"img1": "d0.gif",
"img2": "n0.gif",
"ptime": "11:00"
}
}那么我们首先需要定义一个天气信息类:
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@Generated("org.jsonschema2pojo")
public class Test {
private Weatherinfo weatherinfo;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The weatherinfo
*/
public Weatherinfo getWeatherinfo() {
return weatherinfo;
}
/**
*
* @param weatherinfo
* The weatherinfo
*/
public void setWeatherinfo(Weatherinfo weatherinfo) {
this.weatherinfo = weatherinfo;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(weatherinfo).append(additionalProperties).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Test) == false) {
return false;
}
Test rhs = ((Test) other);
return new EqualsBuilder().append(weatherinfo, rhs.weatherinfo).append(additionalProperties, rhs.additionalProperties).isEquals();
}
}import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@Generated("org.jsonschema2pojo")
public class Weatherinfo {
private String city;
private String cityid;
private String temp1;
private String temp2;
private String weather;
private String img1;
private String img2;
private String ptime;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return
* The city
*/
public String getCity() {
return city;
}
/**
*
* @param city
* The city
*/
public void setCity(String city) {
this.city = city;
}
/**
*
* @return
* The cityid
*/
public String getCityid() {
return cityid;
}
/**
*
* @param cityid
* The cityid
*/
public void setCityid(String cityid) {
this.cityid = cityid;
}
/**
*
* @return
* The temp1
*/
public String getTemp1() {
return temp1;
}
/**
*
* @param temp1
* The temp1
*/
public void setTemp1(String temp1) {
this.temp1 = temp1;
}
/**
*
* @return
* The temp2
*/
public String getTemp2() {
return temp2;
}
/**
*
* @param temp2
* The temp2
*/
public void setTemp2(String temp2) {
this.temp2 = temp2;
}
/**
*
* @return
* The weather
*/
public String getWeather() {
return weather;
}
/**
*
* @param weather
* The weather
*/
public void setWeather(String weather) {
this.weather = weather;
}
/**
*
* @return
* The img1
*/
public String getImg1() {
return img1;
}
/**
*
* @param img1
* The img1
*/
public void setImg1(String img1) {
this.img1 = img1;
}
/**
*
* @return
* The img2
*/
public String getImg2() {
return img2;
}
/**
*
* @param img2
* The img2
*/
public void setImg2(String img2) {
this.img2 = img2;
}
/**
*
* @return
* The ptime
*/
public String getPtime() {
return ptime;
}
/**
*
* @param ptime
* The ptime
*/
public void setPtime(String ptime) {
this.ptime = ptime;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(city).append(cityid).append(temp1).append(temp2).append(weather).append(img1).append(img2).append(ptime).append(additionalProperties).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Weatherinfo) == false) {
return false;
}
Weatherinfo rhs = ((Weatherinfo) other);
return new EqualsBuilder().append(city, rhs.city).append(cityid, rhs.cityid).append(temp1, rhs.temp1).append(temp2, rhs.temp2).append(weather, rhs.weather).append(img1, rhs.img1).append(img2, rhs.img2).append(ptime, rhs.ptime).append(additionalProperties, rhs.additionalProperties).isEquals();
}
}二.网络请求Json 数据,大家知道,在Android 中写一个简单的网络请求任务都需要写 很长一段代码,并且还需要注意android 网络请求必须在子线程中处理,所以跟新UI就得注意了。这里我们使用2013年谷歌大会上提供的开源框架 Volley ,使用这个框架请求网络非常方便,不了解的请看博客:Android Volley完全解析(一),初识Volley的基本用法
因为我们这一节重点是一步解析JSON数据获得 Java bean,所以我自己仿照 Volley 的StringRequest 重新自定义了一个FastJosnRequest 类来使用,使用这个类可以直接获得Java bean实体类,都不需要你自己解析JSON数据了,给你省了很多事情。
FastJson jar包下载链接:http://download.csdn.net/detail/feidu804677682/8341467
FastJosnRequest类的实现如下:
/*
* Copyright (C) 2011 The Android Open Source Project Licensed under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.android.volley.toolbox;
import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Map;
/**
* A canned request for retrieving the response body at a given URL as a String.
*
* @param <T>
*/
public class FastJsonRequest<T> extends Request<T> {
private final Listener<T> mListener;
private final Map<String, String> mParams;
private Map<String, String> mHeaders;
private Class<T> mClass;
/**
* Creates a new request with the given method.
*
* @param method
* the request {@link Method} to use
* @param url
* URL to fetch the string at
* @param params
* Params for the POST request.
* @param headers
* Headers for the POST request.
* @param listener
* Listener to receive the String response
* @param errorListener
* Error listener, or null to ignore errors
*/
public FastJsonRequest(int method, String url, Map<String, String> params,
Map<String, String> headers, Class<T> mClass, Listener<T> listener,
ErrorListener errorListener) {
super(method, url, errorListener);
mListener = listener;
mParams = params;
mHeaders = headers;
this.mClass = mClass;
}
/**
* Creates a new GET or POST request, if request params is null the request
* is GET otherwise POST request.
*
* @param url
* URL to fetch the string at
* @param params
* Params for the POST request.
* @param headers
* Headers for the POST request.
* @param listener
* Listener to receive the String response
* @param errorListener
* Error listener, or null to ignore errors
*/
public FastJsonRequest(String url, Map<String, String> params,
Map<String, String> headers, Class<T> mClass, Listener<T> listener,
ErrorListener errorListener) {
this(null == params ? Method.GET : Method.POST, url, params, headers,
mClass, listener, errorListener);
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return mParams;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
if (null == mHeaders) {
mHeaders = Collections.emptyMap();
}
return mHeaders;
}
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(JSON.parseObject(jsonString, mClass),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
}
这里我直接使用了FastJson jar包来帮助完成解析JSON数据,直接返回给用户实体类,而不许要用户去解析JSON数据。研究过Volley 开源框架的人会发现,我这个类中重写了几个方法,getParams()和getHeaders()两个方法。因为我需要兼容来自用户不同方式的请求(GET和POST)。当使用GET请求的时候 params 和headers 传值 null 进来即可。
三. 接口的使用如下:
package com.example.fastjson;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.FastJsonRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.fastjson.bean.Apk;
import com.example.fastjson.bean.App;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
String url = "http://www.weather.com.cn/data/cityinfo/101010100.html";
RequestQueue mQueue;
String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQueue = Volley.newRequestQueue(this);
mQueue = Volley.newRequestQueue(this);
FastJsonRequest<Test> fRequest = new FastJsonRequest<Test>(url, null,
null, Test.class, new Listener<Test>() {
@Override
public void onResponse(Test response) {
Log.i(TAG, response.getWeatherinfo().toString());
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mQueue.add(fRequest);
}
}
<span style="color:#009900;">Weatherinfo [city=北京, cityId=101010100, temp1=5℃, temp2=-3℃, weather=晴, img1=d0.gif, img2=n0.gif, ptime=11:00]</span>
Android 网络请求json数据,解析json数据,生成对应的java bean类一步到位,快速开发
原文地址:http://blog.csdn.net/feiduclear_up/article/details/42526235