一、JSON数据
1、JSON串访问方式:
2、简介
– JSON(JavaScript Object Notation) 是一种轻量级的数据 交换格式。
– JSON 数据的书写格式:
" KEY " : " VALUE "
JSON 结构有两种结构:
1、对象(表的一列):对象在js中表示为“{}”括起来的内容,数据结构为 {key:value,key:value,...}的键值对的集合。
2、数组(整个表):数组在js中是用中括号“[]”括起来的内容,数据结构为 ["java","javascript","vb",...],取值方式和所有语言中一样,使用索引获取, 字段值的类型可以是 数字、字符串、数组、对象几种。
例子:
对象:
数组:
二、JSONObject
1、简介
JSONObject是一种数据结构,可以理解为JSON格式的数据结构(key-value结构), 是一种重要的数据传输对象,可以使用put方法给JSONObject类的对象添加元素。
2、添加方式
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 1);
jsonObject.put("name", "张三");
jsonObject.put("sex","M");
jsonObject.put("age", 19);
jsonObject.put("major", new String[] {"程序设计","人工智能"});
System.out.println(jsonObject.toString());
HashMap<String,Object> hashMap = new HashMap<>( );
hashMap.put("id", 1);
hashMap.put("name", "张三");
hashMap.put("sex","M");
hashMap.put("age", 19);
hashMap.put("major", new String[] {"程序设计","人工智能"});
System.out.println(new JSONObject(hashMap).toString());
User user = new User();
user.put("id", 1);
user.put("name", "张三");
user.put("sex","M");
user.put("age", 19);
user.put("major", new String[] {"程序设计","人工智能"});
System.out.println(new JSONObject(user));
可以看出,JSONObject可以很方便的把其他对象转换成JSONObject对象,它还可 以将网络接收到的字符串数据转换成JSONObject对象。
String str = "{\"Number\":\"G14060101\",\"Name\":\"张三\",\"Sex\":\"女 \",\"Age\":20}";
JSONObject jsonObject = new JSONObject( str ); //str作为参数传入
3、使用JSONObject解析JSON格式的字符串
(1)JSONObject类提供的常用方法
函数 | 说明 |
---|---|
JSONObject() | 创建一个空的JSONObject对象 |
getJSONObject(String key) | 根据key获取对应的JSONObject对象 |
getJSONArray(String key) | 根据key获取对应的JSONObject数组 |
get(String key) | 根据key值获取JSONObject对象中对应的value值,返回的是Object 对象,需要手动转换为需要的数据类型 |
toString() | 将JSONObject对象转换为json格式的字符串 |
(2)举例
假设从服务器上返回的结果是一个JSON格式的字符串,如下图所示
需求1:获取当前深圳的天气信息情况
从返回的数据中可以发现,当前的天气信息存放在索引为“data”的区域内,需要 通过getJSONObject()方法获取到data区域下的数据。
//根据返回的字符串创建JSONObject对象 JSONObject jsonObject = new JSONObject(str); JSONObject jsonData = jsonObject.getJSONObject("data"); //然后,再通过getString()方法迚行读值操作 String jsonTemplow = jsonData.getString("templow"); String jsonTempHigh = jsonData.getString("temphigh"); String jsonWeather = jsonData.getString("weather"); String jsonTempnow = jsonData.getString("tempnow");
需求2:获取当前深圳的各项指数提醒
从返回的数据中可以发现,各 项指数提醒存放在索引为“index” 的JSON数组内,这需要通过 JSONArray类的相关操作了。接着,再把jsonArray中的数据 按分类进行解析,存放在不同的 ArrayList数组,分别命 名为names、levels、msgs等。
//根据返回的字符串创建JSONObject对象 JSONObject jsonObject = new JSONObject(str); JSONObject jsonData = jsonObject.getJSONObject("data"); JSONArray jsonArray = jsonData.getJSONArray("index"); List<String> names = new ArrayList<String >(); List<String> levels = new ArrayList<String >(); List<String> msgs = new ArrayList<String >(); for (int i=0;i<jsonArray.length();i++){ JSONObject partIndex = jsonArray.getJSONObject(i); String name = partIndex.getString("name"); names.add(name); String level = partIndex.getString("level"); levels.add(level); String msg = partIndex.getString("msg"); msgs.add(msg); }
项目实戓:“聚合数据”天气API
http://v.juhe.cn/weather/index?format=2&cityname=城市名&key=您申请的KEY
注意:在使用该接口之前,首先需要用户进行注册,并获得相应的秘钥KEY
Postman软件
三、代码部分
1、activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
2、MainActivity.java
package com.example.zsjsonobject;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
//1.定义一个字符串变量,用来存放HTTP请求的网络地址
public static final String address = "http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=ccfadb3491e63c1c3556f3ceb19e1237";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//2.调用工具类的sendOkHttpRequest()方法,获取服务器返回的天气信息
HttpUtil.sendOkHttpRequest(address,new okhttp3.Callback(){
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//获取服务器返回的数据
String responseData = response.body().string();
//通过Postman可以发现,未来7天的天气信息存放在索引值为future的JSON数组中
try{
JSONObject jsonObject = new JSONObject(responseData);
JSONObject jsonData = jsonObject.getJSONObject("result");
JSONArray jsonArray = jsonData.getJSONArray("future");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject partFuture = jsonArray.getJSONObject(i);
String temperature = partFuture.getString("temperature");
String weather = partFuture.getString("weather");
String wind = partFuture.getString("wind");
String week = partFuture.getString("week");
String date = partFuture.getString("date");
Log.d("MainActivity","temperature:"+temperature+" "+"weather:"+weather+" "+"wind:"+wind+" "+"week:"+week+" "+"date:"+date);
}
}catch (Exception e){
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
});
}
}
3、HttpUtil.java
v
package com.example.zsjsonobject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class HttpUtil {
public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
//通过okHttp框架的异步请求方式来完成数据的抓取
//1.获得OkHttpClient类的实例
OkHttpClient client = new OkHttpClient();
//2.创建Request对象,并通过属性设置目标网络地址,请求方式等
Request request = new Request.Builder()
.url(address) //将第一个参数传入url属性
.build();
//3.通过OkHttpClient类的实例调用newCall()方法来创建call对象,并把异步请求的结果送入回调接口
client.newCall(request).enqueue(callback);
}
}