Android Network requests json data, parses json data, and generates corresponding java bean classes in one step for quick development

Source: Internet
Author: User

Android Network requests json data, parses json data, and generates corresponding java bean classes in one step for quick development

Android Network requests generally involve image and JSON data. How can I quickly request network JSON data, parse JSON data, and generate the desired Java bean entity class in one step? This involves Android development efficiency. As there are many contacts with the Android network, it is natural to find some good methods to quickly develop the relevant content of the Android network module. Next, we will reveal a quick request for you, parse JSON data to generate the corresponding Java bean entity class method.

Note: Let's explain our ideas first:

1. you can write your own JSON data code for network requests. Of course, I still recommend using the open-source stable framework on the network-Volley. I believe many people should know about this open-source framework, Baidu, this is a useful open-source framework for network requests.

2. the best way to parse JSON data is undoubtedly to use the jar package of the thread tool on the Network (Google's GSON Alibaba FastJson). Here I chose Alibaba's FastJson, which has an advantage, the specific advantages will be explained later.

3. after parsing JSON data, we need to save the data to the object class. We need to define the object class by ourselves. However, when using FastJson to parse JSON data, make sure that the JSON data field and the member variable name of the object class are the same; otherwise, FastJson cannot be parsed (Gson cannot be parsed ), however, FastJson is not used to distinguish between Case sensitivity and Gson, which is why I chose FastJson to parse JSON data.


1. to parse JSON data, we must first define the JSON Data Information Entity class before parsing JSON data and saving the data to the class. However, defining this class does not require the coding of a variable, and errors may occur. Here we take the Chinese weather forecast of a JSON data description, http://www.weather.com.cn/data/cityinfo/101010100.html, the browser request after the JSON data is:

{"Weatherinfo": {"city": "Beijing", "cityid": "101010100", "temp1": "5 ℃", "temp2 ": "-3 ℃", "weather": "Qing", "img1": "d0.gif", "img2": "n0.gif", "ptime "}}
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
 
   additionalProperties = 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 Map
 
   additionalProperties = 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();    }}
   
  
 

The above code won't be typed one by one, right ??? Which Member variable of the class is wrong, which is different from that in Json data? FastJson parsing error !!!!!, So why don't I need to think about the code myself? Here we will teach you a way: Read the blog: Android Json uses jsonschema2pojo to generate a. java file.

II. network request Json data, you know that writing a simple network request task in Android requires a long piece of code, and you also need to note that android network requests must be processed in sub-threads, so pay attention to the new UI. Here we use the open-source framework Volley provided at the 2013 Google conference. It is very convenient to use this framework to request the network. For details, refer to blog: Android Volley full resolution (1 ), basic usage of Volley

Because our focus in this section is to parse JSON data to obtain Java Beans, I customized a FastJosnRequest Class Based on Volley's StringRequest, you can use this class to directly obtain the Java bean entity class without parsing JSON data by yourself, saving you a lot of trouble.

FastJson jar package download link: http://download.csdn.net/detail/feidu804677682/8341467

The FastJosnRequest class is implemented as follows:

/* * 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 
 
   */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);}@Overrideprotected Map
                
                  getParams() throws AuthFailureError {return mParams;}@Overridepublic Map
                 
                   getHeaders() throws AuthFailureError {if (null == mHeaders) {mHeaders = Collections.emptyMap();}return mHeaders;}@Overrideprotected void deliverResponse(T response) {mListener.onResponse(response);}@Overrideprotected 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));}}}
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 
Here, I directly use the FastJson jar package to help parse JSON data and directly return it to the user's entity class, instead of requiring users to parse JSON data. People who have studied the Volley open-source framework will find that I have rewritten several methods in this class: getParams () and getHeaders. Because I need to be compatible with requests (GET and POST) in different ways from users ). When a GET request is used, the params and headers values are null.

3. The interface is used 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
 
   fRequest = new FastJsonRequest
  
   (url, null,null, Test.class, new Listener
   
    () {@Overridepublic void onResponse(Test response) {Log.i(TAG, response.getWeatherinfo().toString());}}, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {}});mQueue.add(fRequest);}}
   
  
 

The result is printed as follows:

Weatherinfo [city = Beijing, cityId = 101010100, temp1 = 5 ℃, temp2 =-3 ℃, weather = sunny, img1108d0.gif, img2=n0.gif, ptime =]

OK. The source code is not included, and the main idea is. You can learn a lot by writing your own code. If you have learned this method, it takes 10 minutes to parse the json data.



Related Article

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.