Android Course of a Sophomore--JSon Analytical Example-Weather Forecast

Keywords: JSON Android xml Java

7:50 PM, 17 March 2017

I opened the pit of XML parsing a month ago and haven't filled it up yet. I finally found that I really don't have time for these old-fashioned data transfers. Now most of them use lightweight JSon to transfer data. This week I saw JSon and felt that the parsing code is much simpler than XML. So now I want to talk about parsing JSon.

Advantages and Disadvantages of JSON and XML

Advantages and disadvantages of JSON

Advantages of JSon

A. Data format is relatively simple, easy to read and write, format is compressed, occupying a small bandwidth;
B. Easy to parse, client JavaScript can simply read JSON data through eval();
C. Supports multiple languages, including ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and other server-side languages, facilitating server-side parsing;
D. In the world of PHP, PHP-JSON and JSON-PHP have already appeared, which are partial to the direct invocation of programs serialized by PHP. Objects and arrays on the server side of PHP can directly generate JSON format, which is convenient for client access and extraction.
E. Because JSON format can be used directly for server-side code, it greatly simplifies the amount of code development on server-side and client-side, and accomplishes tasks unchanged, and is easy to maintain.

Disadvantages of. JSON

A. No XML format is so popular and popular, not so universal as XML.
The promotion of B.JSON format in Web Service is still in its infancy.

Advantages and disadvantages of XML

Advantages of XML

A. The format is uniform and conforms to the standard.
B. It is easy to interact with other systems remotely, and data sharing is more convenient.

Disadvantages of XML

A.XML file is huge, the file format is complex, and the transmission takes up the bandwidth.
B. Both server and client need to spend a lot of code to parse XML, which makes the server and client code extremely complex and difficult to maintain.
C. The way of parsing XML between different browsers on the client side is inconsistent, and many codes need to be written repeatedly.
D. It takes more resources and time to parse XML on the server and client side.

To sum up, it is the mainstream trend to choose JSON parsing.

JSON Format

JSON has two formats, one is the form of key-value pairs, the other is the form of ordered similar arrays.

Unordered Key Value Pair Object

For example, in a schematic diagram, a key/value pair is an unordered jsonObject object that exists in form. An object begins with "{(left curly bracket) and ends with"}"(right curly bracket). Each "name" is followed by a ":" (colon); ""name/value"pairs" are separated by "," (comma).

There is no limit to the type of value here. It can be an array type or another Object or Bool type of data.

Ordered data Array


For example, a schematic diagram is a set of ordered values, which is called jsonArray, and an array is an ordered set of values. An array begins with "[" (left middle bracket) and ends with "]" (right middle bracket). Values are separated by "," (comma).

(Modified from JSON website http://www.json.org/json-zh.html )

JSON parsing class provided in Android

Android provides us with some classes that parse JSON, and these classes are implemented without repeating the guide jar package.

JSONObject

It can be seen as a JSON object, which is the basic unit of the system about the definition of JSON, which contains a pair of key / value values. Its response to External (value output by applying toString() method) calls is embodied in a standard string (e.g. {"JSON": "Hello, World"}, the outermost braces wrapped, where Key and Value are coloned:"separated). It has a slight format for internal behavior, such as initializing a JSONObject instance and adding values by referring to the internal put() method: new JSONObject().put("JSON", "Hello, World!"), separated by commas between Key and Value. Value types include: Boolean, JSONArray, JSONObject, Number, String, or the default JSONObject.NULL object.

JSONStringer

JSON text construction class, according to official interpretation, this class can help create JSON text quickly and conveniently. Its greatest advantage is that it can reduce program exceptions caused by format errors. Referring to this class can automatically and strictly create JSON text in accordance with JSON syntax rules. Each JSONStringer entity can only create a JSON text. Its greatest advantage is that it can reduce program exceptions caused by format errors. Referring to this class can automatically and strictly create JSON text in accordance with JSON syntax rules. Each JSONStringer entity can only create a JSON text correspondingly.

JSONArray

It represents an ordered set of values. Convert it to String output (toString) in the form of square brackets wrapped with commas for values. "Separation (e.g. [value1,value2,value3], you can personally use short code to understand its format more intuitively." The inner part of this class also has query behavior. Both get() and opt() methods can return the specified value through index, and put() method can be used to add or replace the value. Also, the value types of this class can include: Boolean, JSONArray, JSONObject, Number, String, or the default JSONObject.NULL object.

JSONTokener

json analytic class

JSONException

Exceptions used in json

Knowing that there is almost a certain understanding of JSON parsing, then we need to understand the process of parsing JSON in detail through an example - weather forecast.

JSON Analytical Example-Weather Forecast Query

This example can be achieved by inputting the names of cities and counties in China.

Provide you with a free API interface, city = the city behind can be changed

http://wthrcdn.etouch.cn/weather_mini?city=Beijing

Get the JSON source code

Before parsing JSON, we need to know how the JSON data from the API interface GET is.

{"desc":"OK","status":1000,"data":{"wendu":"5","ganmao":"The temperature difference between day and night is large, so it is easy to catch cold. Please add or decrease clothes appropriately. Friends with weak constitution, please pay attention to protection.","forecast":[{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 17℃","type":"Cloudy","low":"Low temperature 6℃","date":"16 Thursday, Sunday"},{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 16℃","type":"Yin","low":"Low temperature 5℃","date":"17 Friday, Sunday"},{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 19℃","type":"Fine","low":"Low temperature 4℃","date":"18 Saturday, Sunday"},{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 18℃","type":"Fine","low":"Low temperature 5℃","date":"19 Sunday, Sunday"},{"fengxiang":"East wind","fengli":"Breeze level","high":"High temperature 15℃","type":"Cloudy","low":"Low temperature 5℃","date":"20 Monday, Sunday"}],"yesterday":{"fl":"Breeze","fx":"Southerly wind","high":"High temperature 16℃","type":"Cloudy","low":"Low temperature 3℃","date":"15 Wednesday, Sunday"},"aqi":"157","city":"Beijing"}}

JSON Data Analysis

You will find that the readability of this JSON code is not generally poor, so what we need to do to get the code is "human flesh parsing".

{        

      "desc":"OK"

         ,"status":1000

<!--Data_Start_here(Type Obj)-->
         ,"data":
        {

<!--Current_Tempreture -->
                "wendu":"5"
<!--Wear_advice-->
           ,"ganmao":"The temperature difference between day and night is large, so it is easy to catch cold. Please add or decrease clothes appropriately. Friends with weak constitution, please pay attention to protection."
<!--Six_Days_Forecast(Type Array)-->
                 ,"forecast":[
                      {"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 17℃","type":"Cloudy","low":"Low temperature 6℃","date":"16 Thursday, Sunday"}
                         ,{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 16℃","type":"Yin","low":"Low temperature 5℃","date":"17 Friday, Sunday"}
                                     ,{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 19℃","type":"Fine","low":"Low temperature 4℃","date":"18 Saturday, Sunday"}
                                     ,{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 18℃","type":"Fine","low":"Low temperature 5℃","date":"19 Sunday, Sunday"}
                                     ,{"fengxiang":"East wind","fengli":"Breeze level","high":"High temperature 15℃","type":"Cloudy","low":"Low temperature 5℃","date":"20 Monday, Sunday"}
                                      ]
<!--Yesterday_Forecast-->
                         ,"yesterday":{"fl":"Breeze","fx":"Southerly wind","high":"High temperature 16℃","type":"Cloudy","low":"Low temperature 3℃","date":"15 Wednesday, Sunday"}
<!--API_NUM-->
         ,"aqi":"160"
<!--Current_City-->
         ,"city":"Beijing"

                 }
<!--Data_End_Here-->

}

This makes it much clearer. As a simple weather query, we need to parse the data under the data key value, and then separate it again.

"data":
        {

<!--Current_Tempreture -->
                "wendu":"5"
<!--Wear_advice-->
           ,"ganmao":"The temperature difference between day and night is large, so it is easy to catch cold. Please add or decrease clothes appropriately. Friends with weak constitution, please pay attention to protection."
<!--Six_Days_Forecast(Type Array)-->
                 ,"forecast":[
                      {"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 17℃","type":"Cloudy","low":"Low temperature 6℃","date":"16 Thursday, Sunday"}
                         ,{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 16℃","type":"Yin","low":"Low temperature 5℃","date":"17 Friday, Sunday"}
                                     ,{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 19℃","type":"Fine","low":"Low temperature 4℃","date":"18 Saturday, Sunday"}
                                     ,{"fengxiang":"Southerly wind","fengli":"Breeze level","high":"High temperature 18℃","type":"Fine","low":"Low temperature 5℃","date":"19 Sunday, Sunday"}
                                     ,{"fengxiang":"East wind","fengli":"Breeze level","high":"High temperature 15℃","type":"Cloudy","low":"Low temperature 5℃","date":"20 Monday, Sunday"}
                                      ]
<!--Yesterday_Forecast-->
                         ,"yesterday":{"fl":"Breeze","fx":"Southerly wind","high":"High temperature 16℃","type":"Cloudy","low":"Low temperature 3℃","date":"15 Wednesday, Sunday"}
<!--API_NUM-->
         ,"aqi":"160"
<!--Current_City-->
         ,"city":"Beijing"

In this way, we can find that there are four key values under this data for Object-type data (wendu, ganmao,city,yesterday) and an Array-type data forecast. There are six Object-type data in Array which store weather data for five days from today, so that after the analysis, we can start to write code to parse JSON data.

Code part

Step 1: Establish the layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    <RelativeLayout
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">
    <EditText
        android:layout_marginLeft="20dp"
        android:id="@+id/et"
        android:hint="Please inout your city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:layout_marginLeft="20dp"
        android:layout_toEndOf="@+id/et"
        android:id="@+id/getInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GetWeatherInfo"
        />
    <TextView
        android:layout_margin="10dp"
        android:textSize="25sp"
        android:id="@+id/tv"
        android:layout_below="@+id/getInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>
</RelativeLayout>

Step 2: Create a tool class (or javaBean) weatherTools.java

public class weatherTools {
    /**Variable meaning:
     * Current_temp--->Real time air temperature
     * Advice---->Clothing recommendation
     * City---->Current city
     * Wind_power---->wind power
     * Wind_dir---->wind direction
     * Max---->Maximum temperature
     * Min---->Minimum temperature
     * Weather---->Weather condition
     * Date---->date
     */
    private String city;
    private String current_temp;
    private String max;
    private String min;
    private String weather;
    private String wind_power;
    private String wind_dir;
    private String date;
    private String advice;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCurrent_temp() {
        return current_temp;
    }

    public void setCurrent_temp(String current_temp) {
        this.current_temp = current_temp;
    }

    public String getMax() {
        return max;
    }

    public void setMax(String max) {
        this.max = max;
    }

    public String getMin() {
        return min;
    }

    public void setMin(String min) {
        this.min = min;
    }

    public String getWeather() {
        return weather;
    }

    public void setWeather(String weather) {
        this.weather = weather;
    }


    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getWind_power() {
        return wind_power;
    }

    public void setWind_power(String wind_power) {
        this.wind_power = wind_power;
    }

    public String getWind_dir() {
        return wind_dir;
    }

    public void setWind_dir(String wind_dir) {
        this.wind_dir = wind_dir;
    }

    public String getAdvice() {
        return advice;
    }

    public void setAdvice(String advice) {
        this.advice = advice;
    }
    @Override
    public String toString() {
        return "Day Weather Forecast:" +
                "\n date " + date+
                "\n City " + city  +
                "\n weather " + weather+
                "\n Clothing recommendation " + advice+
                "\n Real time air temperature" + current_temp +" ℃"+
                "\n Maximum temperature " + max +
                "\n Minimum temperature " + min +
                "\n wind power " + wind_power +
                "\n wind direction " + wind_dir;
    }

}

Step 3: Establish the class JSonFecher to obtain Http server data

import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by li124 on 2017/3/15.
 */

public class JSonFecher {
    //Here's how to set up threads and store and retrieve data
    private String jsonText="";
    //Create a new class to retrieve JSon data
    public  String getJSONText(final URL url){
        //New thread
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                //New Input Stream and Memory Storage Buffer
                InputStream is =null;
                BufferedReader in=null;
                try{
                    //New link to http server
                    HttpURLConnection connection=(HttpURLConnection)url.openConnection();
                    //Setting timeout time
                    connection.setReadTimeout(10000);
                    connection.setConnectTimeout(15000);
                    //Setting Request Mode
                    connection.setRequestMethod("GET");
                    connection.setDoInput(true);
                    connection.connect();
                    //Store the acquired data using the input stream
                    is=connection.getInputStream();
                    //Write data into memory
                    in=new BufferedReader(new InputStreamReader(is));
                    String line="null";
                    while ((line=in.readLine())!=null){
                        //Extract data from memory and assign it to jsonText
                        jsonText+=line;
                    }
                    //Output information to console to confirm receipt of data
                    Log.i("-----------------",jsonText);
                }catch (IOException e){
                    e.printStackTrace();
                    //Close the input stream to save resources
                }finally {
                    {
                        try{
                            in.close();
                            is.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        thread.start();

        try{
            //Thread pause
            Thread.sleep(1000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return jsonText;

    }
}

Step 4: Establish the class JSonUtils for parsing JSON files

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;

/**
 * Created by li124 on 2017/3/15.
 */

public class JSonUtils  {

    public static weatherTools getWeatherTools(URL url){
        //Calling the JSonFecher class to get JSon data from the server
        String jsonText =new JSonFecher().getJSONText(url);
        //The console outputs the acquired data
        System.out.println(jsonText);
        //new an instance of the weatherTools class
        weatherTools weatherTools=new weatherTools();
        //The following code is an operation for JSon data parsing
        try{
            //new is a JSONObject that parses data transmitted by jsonText
            JSONObject jsonObject=new JSONObject(jsonText);
            //Create a JSONObject details parse key value as value after data
            JSONObject detail=jsonObject.getJSONObject("data");
            //Create temp,wear_advice,city to store the value under the corresponding key value
            String temp=detail.getString("wendu");
            String wear_advice=detail.getString("ganmao");
            String city =detail.getString("city");
            String fengli;
            String fengxiang;
            String max;
            String weather;
            String min;
            String date;
            //Create JSONArray to parse data in an array under forecast
            JSONArray ja=(JSONArray)detail.get("forecast");
            //Create a JSONObject to parse the data of each element in the array, where get(int Index) is used to determine the location of the parsed element
            //Here we can add for loop and ArrayList type data to store weather data for the next few days. Because my practical data structure is not so good, I just show the weather data for that day.==
            JSONObject jo=(JSONObject)ja.get(0);
            fengli=jo.getString("fengli");
            fengxiang=jo.getString("fengxiang");
            max=jo.getString("high");
            weather=jo.getString("type");
            min=jo.getString("low");
            date=jo.getString("date");
            //Here we assign variables in weatherTools
            /**Variable meaning:
             * Current_temp--->Real time air temperature
             * Advice---->Clothing recommendation
             * City---->Current city
             * Wind_power---->wind power
             * Wind_dir---->wind direction
             * Max---->Maximum temperature
             * Min---->Minimum temperature
             * Weather---->Weather condition
             * Date---->date
             */
            weatherTools.setCurrent_temp(temp);
            weatherTools.setAdvice(wear_advice);
            weatherTools.setCity(city);
            weatherTools.setWind_power(fengli);
            weatherTools.setWind_dir(fengxiang);
            weatherTools.setMax(max);
            weatherTools.setMin(min);
            weatherTools.setWeather(weather);
            weatherTools.setDate(date);
        }catch (JSONException e){
            e.printStackTrace();
        }
        return weatherTools;
    }
}

Step 5, MainActivity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.net.URL;

public class MainActivity extends AppCompatActivity {
//    private static String url="http://www.weather.com.cn/data/cityinfo/101010100.html";
    //The above comment is used to access the API of China Weather Network, but to get local weather data, you need to know the area code, so it is not recommended.
    //The following API is free of charge, no application times, and can use Chinese characters as keywords to query (thank blogger crazy Wangyb for reprinting!).
    public   String url="http://wthrcdn.etouch.cn/weather_mini?city=Binzhou“;
    Button button;
    EditText et;
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Specified control
        button=(Button) findViewById(R.id.getInfo);
        et=(EditText)findViewById(R.id.et);
        tv=(TextView)findViewById(R.id.tv);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Combining the text obtained by EditText with the URL to generate the URL to be passed for access query
                url="http://wthrcdn.etouch.cn/weather_mini?city="+et.getText().toString();
                GetInfo(view);
            }
        });
    }
    public void GetInfo(View view){
        try{
            Log.i("----------",url);
            URL u =new URL(url);
            weatherTools weatherTools=JSonUtils.getWeatherTools(u);
            System.out.println("TEXT2");
            String message="";
            message=weatherTools.toString();
            tv.setText(message);
           // message="Current Tempreture is :"+weatherTools.getCurrent_temp()+"\nYou should :"+weatherTools.getAdvice()+"\nCurrent city is :"+weatherTools.getCity()+"\nWind_power is :"+weatherTools.getWind_power()+"\nWind_dir is:"+weatherTools.getWind_dir();
            System.out.println(message);
            Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

That's it.

Design sketch

Because my virtual machine can not install input method, API does not know Pinyin, so I directly used the actual test, only achieved the core functions, UI did not take pains to design, feel a little ugly ()

Okay, I'm done. This JSON and XML are so torturous. Especially when parsing JSON manually, it took me a long time to tell whether JSONObject or JSONArray was used. By the way, I forgot to mention one thing, a few examples.

Note:

Example 1: Array contains objects

[{id": 1,"name":"piglet","age": 22}, {id": 2, "name": "kitten", "age": 23},... ].

Example 2: Array can be included in the same object

(1) An object contains an array and two subobjects.

{"root": [{"id":"001", "name":"piglet"}, {"id":"002", "name":"kitten"}, {"id":"003", "name":"puppy"},
"total":3,
"success":true
}

(2) Subobjects can also be nested by objects, and subobjects can be nested by arrays.

{"calendar":
{"calendarlist":
[
{"id":"001", "name":"piglet"}
{"id":"002", "name":"kitten"}
]
}
}

Posted by skurai on Sun, 21 Apr 2019 19:54:35 -0700