The Android network requests JSON data, parses the JSON data, generates the corresponding Java Bean Class one step, and quickly develops

Source: Internet
Author: User

Android network requests generally involve pictures and JSON data, how to quickly request the network JSON data, parse JSON data, and one step to generate the Java Bean entity class you want? This concerns the efficiency of Android development. Because of the more contact with the Android network, naturally found some good ways to quickly develop the content of the Android network module, the next step for everyone to find a quick request, parse the JSON data generated corresponding Java Bean entity class method.

Note: Let us first explain the idea:

1. Network request JSON data code can write their own, of course, I still recommend the use of open source on the network of stable framework---volley, I believe many people should understand this open source framework, do not know Baidu to go, this is a very useful Web request open source framework.

2. Parsing JSON data, the best way is undoubtedly the use of the network on-line tool jar package (Google's Gson Ali Fastjson), I choose here is Ali's Fastjson,fastjson have advantages, the specific advantages explained later.

3. After parsing the JSON data to save the data to the entity class, we need to define the entity class ourselves, but when using Fastjson to parse the JSON data, you must ensure that the JSON data field and the entity class have the same name as the member variable, otherwise Fastjson is not resolved (Gson also parse), but use Fastjson not distinguish between the case of entity class member variables, and Gson distinguish, this is why I chose Fastjson parse JSON data.


I. We need to parse the JSON data, we must first define the JSON data information entity class before we can parse the JSON data and save the data to the class. However, defining this class does not require a variable to strike the code, and it is possible to make an error. Here we take the Chinese weather report a JSON data, http://www.weather.com.cn/data/cityinfo/101010100.html, the browser request after the JSON data obtained is:

{"    Weatherinfo": {        "city": "Beijing",        "Cityid": "101010100",        "Temp1": "5 ℃",        "Temp2": " -3℃",        " Weather ":" Clear ","        img1 ":" D0.gif ",        " Img2 ":" N0.gif ",        " Ptime ":" 11:00AM "    }}
So first we need to define a weather information class:

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 Weatherin    Fo }/** * * @param weatherinfo * the weatherinfo * */public void Setweatherinfo (Weatherinfo weathe    Rinfo) {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 (Additionalpropert    ies). Tohashcode ();        } @Override public boolean equals (Object) {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). A PPend (TEMP2). Append (Weather). Append (IMG1). Append (Img2). Append (Ptime). Append (additionalproperties). Tohashcode ();        } @Override public boolean equals (Object) {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 (); }}

You're not going to knock on one of these codes??? Which of the member variables in the category is wrong, not the same as in the JSON data? So the Fastjson is wrong,!!!!!. , then how do you not want to knock the code yourself? Here's a way to teach you: Read the blog: Android Json uses Jsonschema2pojo to generate. java file files.

Two. Network request JSON data, you know, write a simple network request task in Android need to write a long code, and also need to note that the Android network request must be processed in the sub-thread, so with the new UI should be noted. Here we use the 2013 Google Conference provided by the open source framework volley, use this framework to request the network is very convenient, do not understand the blog: Android volley fully Parse (a), the basic usage of the first knowledge volley

Because our focus in this section is to parse the JSON data for Java beans in one step, I have re-defined a Fastjosnrequest class to use in my own volley stringrequest, using this class to get the Java Bean entity class directly. You do not need to parse the JSON data yourself, to save you a lot of things.

Fastjson jar Package Download Link: http://download.csdn.net/detail/feidu804677682/8341467

The Fastjosnrequest class is implemented as follows:

/* Copyright (C) The Android Open Source Project Licensed under the Apache * License, Version 2.0 (the "License"); You are not a use of this file except in * compliance with the License. Obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 unless required by applicable law * o  R agreed to writing, software distributed under the License are * distributed on a "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> ML Istener;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 @ * @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);} @Overrideprotected map<string, String> getparams () throws Authfailureerror {return mparams;} @Overridepublic map<string, String> getheaders () throws Authfailureerror {if (null = = Mheaders) {mheaders = Collections.emptymap ();} return mheaders;} @Overrideprotected void Deliverresponse (T response) {mlistener.onresponse (response);} @Overrideprotected 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));}}
Here I use the Fastjson jar package directly to help parse JSON data and return it directly to the user entity class without having to parse the JSON data. People who have studied the volley open source framework will find that I have overridden several methods in this class, Getparams () and Getheaders () two methods. Because I need to be compatible with requests from the user in different ways (get and post). When a GET request is used, the params and headers pass the value NULL in.

Three. The use of the interface is as follows:

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"; @Overrideprotected 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> () {@Overridepublic void Onresponse (Test response) {log.i (TAG, Response.getweatherinfo (). toString ());}}, New Errorlistener () {@Overridepublic void Onerrorresponse (Volleyerror error) {}}); Mqueue.add (frequest);}}

The results are printed as follows:

<span style= "color: #009900;" >weatherinfo [city= Beijing, cityid=101010100, Temp1=5℃, Temp2=-3℃, Weather= Ching, Img1=d0.gif, Img2=n0.gif, ptime=11:00]< /SPAN>

OK, Finish. The source code is not attached, the main is the idea. Write your own code, you can learn a lot of things. If you learn this approach, then parsing the JSON data would have been a morning break with code that would take only 10 minutes to get it done.



The Android network requests JSON data, parses the JSON data, generates the corresponding Java Bean Class one step, and quickly develops

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.