Android之JSON格式数据解析

article/2025/9/28 8:02:50
JSON:JavaScript 对象表示法(JavaScript Object Notation)。独立于语言和平台,比 XML 更小、更快,更易解析。如今JSON数据已经成为了互联网中大多数数据的传递方式,所以必须要熟练掌握。

Android平台自带了JSON解析的相关API,可以将文件、输入流中的数据转化为JSON对象,然后从对象中获取JSON保存的数据内容。


Android的JSON解析部分都在包org.json下,主要有以下几个类: 
JSONObject:可以看作是一个json对象,这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。它对外部(External:应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{"JSON": "Hello, World"},最外被大括号包裹,其中的Key和Value被冒号":"分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之间是以逗号","分隔。Value的类型包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

JSONStringer:json文本构建类 ,根据官方的解释,这个类可以帮助快速和便捷的创建JSON text。其最大的优点在于可以减少由于 格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。

JSONArray:它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如:[value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为,get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

JSONTokener:json解析类
JSONException:json中用到的异常

下面以聚合数据空气质量城市空气PM2.5指数数据接口为例来演示JSON格式数据的解析。
聚合数据空气质量城市空气PM2.5指数数据接口API文档参见: http://www.juhe.cn/docs/api/id/33/aid/79
JSON返回示例:
{ /*JSONObject*/
    "resultcode": "200",
    "reason": "SUCCESSED!",
    "result": [ /*JSONArray*/
        { /*JSONObject*/
            "city": "苏州",  /*城市*/
            "PM2.5": "73",  /*PM2.5指数*/
            "AQI": "98",    /*空气质量指数*/
            "quality": "良", /*空气质量*/
            "PM10": "50",/*PM10*/
            "CO": "0.79",  /*一氧化碳*/
            "NO2": "65",  /*二氧化氮*/
            "O3": "28",    /*臭氧*/
            "SO2": "41",  /*二氧化硫*/
            "time": "2014-12-26 11:48:40"/*更新时间*/  
        }
    ],
    "error_code": 0
}

实例:JSONDemo
运行效果:

代码清单:
布局文件:activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><LinearLayout android:layout_width="match_parent"android:layout_height="wrap_content" android:orientation="horizontal" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:gravity="center"android:text="城市:"android:textSize="23sp" /><EditText android:id="@+id/city"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="3"android:inputType="text" />"</LinearLayout><Buttonandroid:id="@+id/query"android:layout_width="match_parent"android:layout_height="wrap_content" android:text="查询" android:textSize="23sp" /><TextViewandroid:id="@+id/result"android:layout_width="match_parent"android:layout_height="match_parent" />
</LinearLayout>

Java源代码文件:MainActivity.java
package com.rainsong.jsondemo;import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends Activity {EditText et_city;Button btn_query;TextView tv_result;QueryTask task;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et_city = (EditText)findViewById(R.id.city);tv_result = (TextView)findViewById(R.id.result);btn_query = (Button)findViewById(R.id.query);btn_query.setOnClickListener(new OnClickListener() {public void onClick(View view) {String city = et_city.getText().toString();if (city.length() < 1) {Toast.makeText(MainActivity.this, "请输入城市名",Toast.LENGTH_LONG).show();return;}task = new QueryTask(MainActivity.this, tv_result);task.execute(city);}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

Java源代码文件:QueryTask.java
package com.rainsong.jsondemo;import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
import android.widget.Toast;public class QueryTask extends AsyncTask<String, Void, String> {Context context;TextView tv_result;private static final String JUHE_URL_ENVIRONMENT_AIR_PM = "http://web.juhe.cn:8080/environment/air/pm";private static final String JUHE_APPKEY = "你申请的APPKEY值";public QueryTask(Context context, TextView tv_result) {// TODO Auto-generated constructor stubsuper();this.context = context;this.tv_result = tv_result; }@Overrideprotected String doInBackground(String... params) {String city = params[0];ArrayList<NameValuePair> headerList = new ArrayList<NameValuePair>();headerList.add(new BasicNameValuePair("Content-Type", "text/html; charset=utf-8"));String targetUrl = JUHE_URL_ENVIRONMENT_AIR_PM;ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();paramList.add(new BasicNameValuePair("key", JUHE_APPKEY));paramList.add(new BasicNameValuePair("dtype", "json"));paramList.add(new BasicNameValuePair("city", city));for (int i = 0; i < paramList.size(); i++) {NameValuePair nowPair = paramList.get(i);String value = nowPair.getValue();try {value = URLEncoder.encode(value, "UTF-8");} catch (Exception e) {}if (i == 0) {targetUrl += ("?" + nowPair.getName() + "=" + value);} else {targetUrl += ("&" + nowPair.getName() + "=" + value);}}HttpGet httpRequest = new HttpGet(targetUrl);try {for (int i = 0; i < headerList.size(); i++) {httpRequest.addHeader(headerList.get(i).getName(),headerList.get(i).getValue());}HttpClient httpClient = new DefaultHttpClient();HttpResponse httpResponse = httpClient.execute(httpRequest);if (httpResponse.getStatusLine().getStatusCode() == 200) {String strResult = EntityUtils.toString(httpResponse.getEntity());return strResult;} else {return null;}} catch (IOException e) {e.printStackTrace();}return null;}@Override  protected void onPostExecute(String result) {if (result != null) {try {JSONObject jsonObject = new JSONObject(result);int resultCode = jsonObject.getInt("resultcode");if (resultCode == 200) {JSONArray resultJsonArray = jsonObject.getJSONArray("result");JSONObject resultJsonObject = resultJsonArray.getJSONObject(0);String output = context.getString(R.string.city) + ": " + resultJsonObject.getString("city") + "\n"+ context.getString(R.string.PM25) + ": " + resultJsonObject.getString("PM2.5") + "\n"+ context.getString(R.string.AQI) + ": " + resultJsonObject.getString("AQI") + "\n"+ context.getString(R.string.quality) + ": " + resultJsonObject.getString("quality") + "\n"+ context.getString(R.string.PM10) + ": " + resultJsonObject.getString("PM10") + "\n"+ context.getString(R.string.CO) + ": " + resultJsonObject.getString("CO") + "\n"+ context.getString(R.string.NO2) + ": " + resultJsonObject.getString("NO2") + "\n"+ context.getString(R.string.O3) + ": " + resultJsonObject.getString("O3") + "\n"+ context.getString(R.string.SO2) + ": " + resultJsonObject.getString("SO2") + "\n"+ context.getString(R.string.time) + ": " + resultJsonObject.getString("time") + "\n";tv_result.setText(output);} else if (resultCode == 202) {String reason = jsonObject.getString("reason");tv_result.setText(reason);} else {Toast.makeText(context, "查询失败",Toast.LENGTH_LONG).show();tv_result.setText("");}} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}} else {Toast.makeText(context, "查询失败",Toast.LENGTH_LONG).show();tv_result.setText("");}}  }

字符串资源:string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources><string name="app_name">JSONDemo</string><string name="action_settings">Settings</string><string name="hello_world">Hello world!</string><string name="city">城市</string><string name="PM25">PM2.5指数</string><string name="AQI">空气质量指数</string><string name="quality">空气质量</string><string name="PM10">PM10</string><string name="CO">一氧化碳</string><string name="NO2">二氧化氮</string><string name="O3">臭氧</string><string name="SO2">二氧化硫</string><string name="time">更新时间</string></resources>


API知识点
public class 
JSONObject
extends Object

org.json.JSONObject

Class Overview
A modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles or NULL. Values may not be null, NaNs, infinities, or of any type not listed here. 

JSONObject(String json) 
Creates a new JSONObject with name/value mappings from the JSON string.
 
Object  get(String name) 
Returns the value mapped by name. 

int  getInt(String name) 
Returns the value mapped by name if it exists and is an int or can be coerced to an int. 

String  getString(String name) 
Returns the value mapped by name if it exists, coercing it if necessary. 

JSONArray  getJSONArray(String name) 
Returns the value mapped by name if it exists and is a JSONArray. 

public class 
JSONArray
extends Object

org.json.JSONArray

Class Overview
A dense indexed sequence of values. Values may be any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or NULL. Values may not be NaNs, infinities, or of any type not listed here. 

JSONObject  getJSONObject(int index) 

Returns the value at index if it exists and is a JSONObject. 



http://chatgpt.dhexx.cn/article/PVAZEXLL.shtml

相关文章

Python提取JSON格式数据

文章目录 前言&#xff1a;一、JSON使用1.导入json的包2.常用的方法 二、实战1.json.loads()2.jsonpath 前言&#xff1a; 我们经常会用到json数据&#xff0c;json数据格式主要是用来和不同语言之间进行交互比如你要给java端的提供数据&#xff0c;你需要将自己的数据转换为j…

解析JSON格式数据常见方法

待解析的JSON格式的文件如下&#xff1a; [{"id":"5", "version":"1.0", "name":"xiaowang"}, {"id":"10", "version":"2.0", "name":"lisi"}] 一、…

JSON.parseObject 解析JSON格式数据

fastjson是阿里巴巴开源产品之一&#xff0c;解析速度快。 下载地址(maven仓库)&#xff1a;https://mvnrepository.com/artifact/com.alibaba/fastjson/1.2.53 // 当待解析的JSON字符串是简单对象类型的&#xff0c;即用大括号包围&#xff0c;此时采用JSONObject对象来处理…

JQuery 发送Json格式数据

简述&#xff1a; 需要封装一组Json格式的数据到服务器 知识点&#xff1a; 1. 调用jquery.json的库 2. AJAX Post 请求 Jquery下载地址 http://jquery.com/download/ Jquery.json http://code.google.com/p/jquery-json/ 代码&#xff1a; testSendJson.jsp <% page…

Json格式字符串转换成Json格式数据

1、json格式字符串 2、将json格式字符串转换成json格式 //json格式的字符串 String str "{ \"people\": [\n" "\n" "{ \"firstName\": \"Brett\", \"lastName\":\"McLaughlin\", \"email\&…

数据库中存储Json格式数据

在数据库中存储Json格式数据 1、表字段类型 json 2、Java代码有两种方式&#xff1a; 方式一 &#xff1a;属性定义成String类型。 往数据库中存储的值 必须为JSON格式的字符串&#xff0c;因为数据库中会做一次校验。 缺点&#xff1a;往数据库中存的数据是String类型&…

Mysql存储json格式数据

Mysql5.7版本以后新增的功能&#xff0c;Mysql提供了一个原生的Json类型&#xff0c;Json值将不再以字符串的形式存储&#xff0c;而是采用一种允许快速读取文本元素&#xff08;document elements&#xff09;的内部二进制&#xff08;internal binary&#xff09;格式。在Jso…

多路复用技术之时分复用

多路复用技术是通信技术领域的一个专业名词&#xff0c;从字面上的意思去理解就是将多路信号按照一定的规则共用同一条信道进行传输。 一、多路复用技术的分类 多路复用技术通常分为频分多路复用、时分多路复用、波分多路复用、码分多址和空分多址。 二、时分多路复用原理 …

“分集”与“复用”辨析

【注&#xff1a;本文中几乎所有文字与图片均来自网络&#xff0c;本人仅做了整理与归纳&#xff01;】 文章目录 分集与复用1. 分集与复用的概念1.1 分集1.2 复用 2. 分集与复用的目的2.1 分集的目的2.2 分集阶数与分集增益2.3 复用的目的 3. 分集与复用的分类3.1 分集技术3.…

认识LTE(七):LTE中的两种无反馈模式:发射分集(TM2)和开环空分复用(TM3)

认识LTE(七)&#xff1a;LTE中的两种无反馈模式&#xff1a;发射分集&#xff08;TM2&#xff09;和开环空分复用&#xff08;TM3&#xff09; 文章目录 认识LTE(七)&#xff1a;LTE中的两种无反馈模式&#xff1a;发射分集&#xff08;TM2&#xff09;和开环空分复用&#xff…

认识LTE(八):LTE中的反馈:闭环空分复用(TM4)

认识LTE(八)&#xff1a;LTE中的反馈&#xff1a;闭环空分复用&#xff08;TM4&#xff09; 文章目录 认识LTE(八)&#xff1a;LTE中的反馈&#xff1a;闭环空分复用&#xff08;TM4&#xff09;零.代码地址一.TM4到底反馈了什么&#xff1f;二.CQI反馈二.PMI 三.RI四.总结 零.…

图解通信原理与案例分析-21:4G LTE多天线技术--天线端口、码流、分集Diveristy、波束赋形BF、空分复用MIMO、空分多址

目录 前言&#xff1a; 第1章 MIMO多天线技术概述 1.1 三大目的 1.2 六大分类 第2章 单天线SISO&#xff08;单输入单输出&#xff09; 2.1 概述 2.2 实现原理--多路“异频”《发送接收》对 第3章 接收分集MISO&#xff08;多输入单输出&#xff09;&#xff1a;冗余接…

[4G5G专题-28]:架构-什么是多天线技术与5G大规模天线阵列、波束赋形、高阶空分复用?

目录 第1章 多天线技术概述 1.1 LTE的多天线技术回顾 1.2 5G大规模天线阵列、波束赋形以及其动机 第2章 什么是波束赋形 2.1 波束赋形与大规模天线阵列的关系 2.2 波束赋形的定义 2.3 波束赋形要回答和解决的两个问题 2.4 常见的波束赋形相关的专业术语 第3章 Active …

复用,多址的区分以及其涉及的相关数据速率

复用技术 为了让尽可能多的手机使用同一个频段&#xff0c;无线通信设计了多址复用技术&#xff1a; 时分多路复用&#xff08;Time Division Multiplexing&#xff0c;TDM)要求各个子通道按时间片轮流地占用整个带宽。时间片的大小可以按一次传送一位、一个字节或一个固定大…

王道 —— 操作系统的四个特征

1、知识总览 操作系统有并发、共享、虚拟、异步四个基本特征&#xff0c;并发和共享是两个最基本的特征&#xff0c;二者互为存在条件&#xff1b; 2、操作系统的特征 —— 并发 并发&#xff1a;指两个或者多个时间在同一时间间隔内发生。这些事件宏观上是同时发生的&#x…

操作系统学习笔记——总体总结

看书太慢容易抓不住重点&#xff0c;所以在此按照操作系统的主要内容分别查网上博客资料进行学习。 一、引论 操作系统基本特性&#xff1a; 并发&#xff1a; 1.并行与并发&#xff1a;并行性是指两个或多个时间在同一时刻发送&#xff1b;并发性是指两个或多是事件在同一…

数据库脏读、不可重复读、幻读

1. 脏读 &#xff1a;脏读就是指当一个事务正在访问数据&#xff0c;并且对数据进行了修改&#xff0c;而这种修改还没有提交到数据库中&#xff0c;这时&#xff0c;另外一个事务也访问这个数据&#xff0c;然后使用了这个数据。 2. 不可重复读 &#xff1a;是指在一个事务内&…

关于可重复读和幻读

最近看到MySQL隔离性的知识&#xff0c;发现网上很多人说可重复读所针对的操作是update&#xff0c;然后亲自试验了一把&#xff0c;见下文。 首先我们知道在读提交隔离级别下&#xff0c;同一事物A中以相同的查询语句可能得到的结果不一致的情况&#xff0c;即不可重复读。这是…

可重复读如何解决幻读

学习之前的疑问&#xff1a; 可重复读的概念 与 不可重复读的概念 行锁gap锁(间隙锁) 快照读 与 当前读区别 快照读中的MVCC 当前读中的gap锁 和 行锁 前几天面试时被问到了mysql可重复读如何解决幻读的问题&#xff0c;之前脑子中的概念只有增加了共享锁和排他锁进行避免&…

MySQL(四)—MVCC实现可重复读的原理

文章目录 一、MVCC概况二、MVCC实现原理1.两或三个隐藏字段。2.undo log3.一个数组4.ReadView 三、举例验证MVCC原理参考文献 一、MVCC概况 MVCC是什么&#xff1f;MVCC即多版本控制协议&#xff0c;InnoDB实现了MVCC作版本控制&#xff0c;防止不该被当前事务看到的数据看到。…