Android 网络请求json数据,解析json数据,生成对应的java bean类一步到位,快速开发
来源:互联网 发布:广场舞短袖上衣淘宝网 编辑:程序博客网 时间:2024/05/02 04:50
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数据是:
那么我们首先需要定义一个天气信息类:123456789101112{
"weatherinfo"
: {
"city"
:
"北京"
,
"cityid"
:
"101010100"
,
"temp1"
:
"5℃"
,
"temp2"
:
"-3℃"
,
"weather"
:
"晴"
,
"img1"
:
"d0.gif"
,
"img2"
:
"n0.gif"
,
"ptime"
:
"11:00"
}
}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import
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();
}
}</string,></string,></string,>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195import
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();
}
}</string,></string,></string,>
上面的这些代码你们不会一个一个去敲吧???万一 类的哪个成员变量敲错了,跟Json数据里面的不一样?那么 FastJson 就解析出错了啊!!!!!,那么怎么才不许要自己敲这些代码呢? 这里教大家一个办法:请看博客:Android Json 使用jsonschema2pojo生成.java文件文件 。二.网络请求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类的实现如下:
这里我直接使用了FastJson jar包来帮助完成解析JSON数据,直接返回给用户实体类,而不许要用户去解析JSON数据。研究过Volley 开源框架的人会发现,我这个类中重写了几个方法,getParams()和getHeaders()两个方法。因为我需要兼容来自用户不同方式的请求(GET和POST)。当使用GET请求的时候 params 和headers 传值 null 进来即可。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115/*
* 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));
}
}
}
</t></string,></string,></t></t></string,></string,></t></t></string,></string,></t></string,></string,></t></t></t></t>
三. 接口的使用如下:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package
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);
}
}
</test></test></test>
结果打印如下:1<span style=
"color:#009900;"
>Weatherinfo [city=北京, cityId=
101010100
, temp1=
5
℃, temp2=-
3
℃, weather=晴, img1=d0.gif, img2=n0.gif, ptime=
11
:
00
]</span>
OK,完成。源代码就不附了,主要的是思路。自己写代码,可以学到很多东西。如果你学会了这种方法,那么解析json数据本来要一个上午敲代码的现在只需要10分钟就搞定。
- Android 网络请求json数据,解析json数据,生成对应的java bean类一步到位,快速开发
- Android 网络请求json数据,解析json数据,生成对应的java bean类一步到位,快速开发
- ndroid 网络请求json数据,解析json数据,生成对应的java bean类一步到位,快速开发
- 【Android网络开发の4】解析和生成JSON数据
- Json解析网络请求数据
- Android--网络请求与json数据解析的使用
- 通过GSON 解析Json数据,但是不创建JAVA Bean的方式,获取对应的值
- Android开发中使用fastJSON将json格式的数据快速解析生成实体类并附上实体类生成器
- android解析JSON,XML数据的请求网络工具类
- Android使用HttpURLConnection请求网络返回JSON数据并解析
- iOS 网络数据请求和Json 解析
- Android开发json数据的生成
- Json 数据的解析 ,生成
- 请求网络数据JSON
- Java从网络中请求获取JSon数据以及解析JSON数据----(自创,请注明)
- Android开发--Json数据的解析
- Android Volley请求json数据,fastJson解析json数据
- 【Android眼中的IOS】IOS开发快速解析Json数据(仿Android解析流程)
- Android面试(三)(转)
- 沙盒(sandbox) 及 NSFileManager
- C++ cin.getline()函数的使用
- 人脸图像数据库(完整版)
- Linux Shell 编程语法
- Android 网络请求json数据,解析json数据,生成对应的java bean类一步到位,快速开发
- 程序在别的机器上无法运行的问题
- Android Studio的library项目依赖,Jar包,常用快捷键的对比
- JS or C#?不存在的脚本之争(UnityScript 不是 Javascript)
- Android面试(三)(转)
- CoreText
- python3.0学习五 快捷键应用
- 基于Flume的美团日志收集系统(二)改进和优化
- 1035. Password (20)