編輯:關於Android編程
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 MapadditionalProperties = new HashMap (); /** * * @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 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 MapadditionalProperties = new HashMap (); /** * * @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 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這裡我直接使用了FastJson jar包來幫助完成解析JSON數據,直接返回給用戶實體類,而不許要用戶去解析JSON數據。研究過Volley 開源框架的人會發現,我這個類中重寫了幾個方法,getParams()和getHeaders()兩個方法。因為我需要兼容來自用戶不同方式的請求(GET和POST)。當使用GET請求的時候 params 和headers 傳值 null 進來即可。*/ public class FastJsonRequest extends Request { private final Listener mListener; private final Map mParams; private Map mHeaders; private Class 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 params, Map headers, Class mClass, Listener 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 params, Map headers, Class mClass, Listener listener, ErrorListener errorListener) { this(null == params ? Method.GET : Method.POST, url, params, headers, mClass, listener, errorListener); } @Override protected Map getParams() throws AuthFailureError { return mParams; } @Override public Map getHeaders() throws AuthFailureError { if (null == mHeaders) { mHeaders = Collections.emptyMap(); } return mHeaders; } @Override protected void deliverResponse(T response) { mListener.onResponse(response); } @Override protected Response 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)); } } }
三. 接口的使用如下:
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); FastJsonRequestfRequest = new FastJsonRequest (url, null, null, Test.class, new Listener () { @Override public void onResponse(Test response) { Log.i(TAG, response.getWeatherinfo().toString()); } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); mQueue.add(fRequest); } }
Weatherinfo [city=北京, cityId=101010100, temp1=5℃, temp2=-3℃, weather=晴, img1=d0.gif, img2=n0.gif, ptime=11:00]
之前想要給statusbar和toolbar實現這樣的效果:為使得statusbar變為透明,在自定義theme中給statusbar添加了以下屬性: &l
前言 關鍵字:Vitamio、VPlayer、Android播放器、Android影音、Android開源播放器 本章節把Android萬能播放器本地播放的主要功能(
1. Message 消息,理解為線程間通訊的數據單元。例如後台線程在處理數據完畢後需要更新UI,則可發送一條包含更新信息的Message給UI線程。 2.
Animator最早出現在Android 3.0 中,和之前的Animation框架相比,Animator更加的靈活並且具有更多的功能,官方推薦使用Animator代替A