Android网络请求之JSON

JSON(JavaScript Object Notation,JS对象简谱)是一种轻量级的数据交换格式。

//简单的JSON格式就是普通的键值对形式,例如:
{
	"city":"深圳",
	"updata_time":"20.58",
	"wea":"晴"
}

//嵌套的JSON格式,例如:
{
	"name":"小明",
	"phone_number":["1234","2345","4567"],
	"father":{"name":"大明","phone_number":"6789"}
}

1.JSON数据解析

  • JSONObject 表示一个JSON节点
  • JSONObject.opt(“key”) 根据键获取值,如果没有匹配的键,则返回空。(推荐)
  • JSONObject.get(“key”) 根据键获取值,如果没有匹配的键,则抛出异常。

根据值的类型获取

  • JSONObject.optString(“key”) //字符串
  • JSONObject.optlnt(“key”) //数字
  • JSONObject.optBoolean(“key”) //布尔
  • JSONObject.optJSONObject(“key”) //嵌套
  • JSONObject.optJSONArray(“key”) //数组
package com.example.networktest3111;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.networktest3111.util.NetUtil;
import com.example.networktest3111.util.NetUtil3;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    private TextView tvContent;
    private EditText et_city;
    private EditText et_weathr;
    private EditText et_wemDay;
    private EditText et_wemNight;
    private EditText et_winSpeed;


    private Handler mHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                String strData = (String) msg.obj;
                tvContent.setText(strData);
                parseJsonDataAndShow(strData);
                Toast.makeText(MainActivity.this,"主线程收到来自网络的消息啦!",Toast.LENGTH_SHORT).show();
            }

        }
    };

    /**
     * json数据示例
     * {
     *     "cityid":"101120101",
     *     "city":"济南",
     *     "update_time":"20:55",
     *     "wea":"晴",
     *     "wea_img":"qing",
     *     "tem":"11",
     *     "tem_day":"17",
     *     "tem_night":"7",
     *     "win":"东南风 ",
     *     "win_speed":"1级",
     *     "win_meter":"小于12km/h",
     *     "air":"73"
     * }
     *
     * @param jsonStr
     */
    public void parseJsonDataAndShow(String jsonStr){
        //JSONobject拿到JSON的一个节点
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            String cityId = jsonObject.optString("cityid");
            String city = jsonObject.optString("city");
            String updateTime = jsonObject.optString("update_time");
            String weather = jsonObject.optString("wea");
            String weatherImg = jsonObject.optString("wea_img");
            String tem = jsonObject.optString("tem");
            String wemDay = jsonObject.optString("tem_day");
            String wemNight = jsonObject.optString("tem_night");
            String win = jsonObject.optString("win");
            String winSpeed = jsonObject.optString("win_speed");
            String winMeter = jsonObject.optString("win_meter");
            String air = jsonObject.optString("air");

            //显示JSON数据

            et_city.setText(city);
            et_weathr.setText(weather);
            et_wemDay.setText(wemDay);
            et_wemNight.setText(wemNight);
            et_winSpeed.setText(winSpeed);

        }catch(JSONException e){
            e.printStackTrace();
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvContent = findViewById(R.id.tv_content);
        et_city = findViewById(R.id.et_city);
        et_weathr = findViewById(R.id.et_weathr);
        et_wemDay = findViewById(R.id.et_wemDay);
        et_wemNight = findViewById(R.id.et_wemNight);
        et_winSpeed = findViewById(R.id.et_winSpeed);
    }

    public void start(View view) {

        // 做一个耗时任务
        new Thread(new Runnable() {
            @Override
            public void run() {
                String stringFromNet = getStringFromNet();

                Message message = new Message();
                message.what = 0;
                message.obj = stringFromNet;

                mHandler.sendMessage(message);

            }
        }).start();

        Toast.makeText(this,"开启子线程请求网络!",Toast.LENGTH_SHORT).show();

    }


    private String getStringFromNet() {

        return NetUtil3.getWeatherofCity("济南");
        }
 }

Android网络请求之JSON_第1张图片

2.使用GSON库解析JSON数据到JavaBean

  • GSON库的引入
  • 把json字符串转换成JavaBean对象
  • 把JavaBean对象转换成json字符串

(1)首先,创建一个WeatherBean.java,将上面所有用到的数据写出

public class WeatherBean {
 	private String cityid;
    private String city;
    private String wea;
    private String wea_img;
    private String tem ;
    private String tem_day;
    private String tem_night;
    private String win;
    private String win_speed;
    private String win_meter;
    private String air;
   }

之后右键单击选Generate… -->Getter and Setter全选点OK–>Genernate…选toString()
Android网络请求之JSON_第2张图片
Android网络请求之JSON_第3张图片
Android网络请求之JSON_第4张图片

package com.example.networktest3111;

public class WeatherBean {

    //注意此处取得名字一定要和JSON的键名相同
    //此为可以用@SerializedName("cityid")    private String cityId;来修改键名
    // 则可以用cityId替换cityid,但是需要每一个都修改一下
    private String cityid;
    private String city;
    private String wea;
    private String wea_img;
    private String tem ;
    private String tem_day;
    private String tem_night;
    private String win;
    private String win_speed;
    private String win_meter;
    private String air;


    public String getCityid() {
        return cityid;
    }

    public void setCityid(String cityid) {
        this.cityid = cityid;
    }

    public String getCity() {
        return city;
    }

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

    public String getWea() {
        return wea;
    }

    public void setWea(String wea) {
        this.wea = wea;
    }

    public String getWea_img() {
        return wea_img;
    }

    public void setWea_img(String wea_img) {
        this.wea_img = wea_img;
    }

    public String getTem() {
        return tem;
    }

    public void setTem(String tem) {
        this.tem = tem;
    }

    public String getTem_day() {
        return tem_day;
    }

    public void setTem_day(String tem_day) {
        this.tem_day = tem_day;
    }

    public String getTem_night() {
        return tem_night;
    }

    public void setTem_night(String tem_night) {
        this.tem_night = tem_night;
    }

    public String getWin() {
        return win;
    }

    public void setWin(String win) {
        this.win = win;
    }

    public String getWin_speed() {
        return win_speed;
    }

    public void setWin_speed(String win_speed) {
        this.win_speed = win_speed;
    }

    public String getWin_meter() {
        return win_meter;
    }

    public void setWin_meter(String win_meter) {
        this.win_meter = win_meter;
    }

    public String getAir() {
        return air;
    }

    public void setAir(String air) {
        this.air = air;
    }


    @Override
    public String toString() {
        return "WeatherBean{" +
                "cityId='" + cityid + '\'' +
                ", city='" + city + '\'' +
                ", weather='" + wea + '\'' +
                ", weatherImg='" + wea_img + '\'' +
                ", tem='" + tem + '\'' +
                ", wemDay='" + tem_day + '\'' +
                ", wemNigh='" + tem_night + '\'' +
                ", win='" + win + '\'' +
                ", winSpeed='" + win_speed + '\'' +
                ", winMeter='" + win_meter + '\'' +
                ", air='" + air + '\'' +
                '}';
    }
}

(2)在build.gradle(:app)的dependencies添加gson依赖

implementation("com.google.code.gson:gson:2.8.5")

(3)在MainActivity.java的parseJsonDataAndShow函数中添加如下语句

			Gson gson = new Gson();
            // 把json字符串直接转换成JavaBean对象
            WeatherBean weatherBean = gson.fromJson(jsonStr,WeatherBean.class);
            Log.d("fan","--weatherBean--"+weatherBean.toString());

            //将JavaBean对象转换成json字符串
            String jsonWeather = gson.toJson(weatherBean);
            Log.d("fan","--jsonWeather--"+jsonWeather);

运行结果:
在这里插入图片描述

你可能感兴趣的:(Android,Studio,android,json)