`
喵喵大神
  • 浏览: 37033 次
文章分类
社区版块
存档分类
最新评论

Android之JSON格式数据解析

阅读更多

转载:http://blog.csdn.net/hantangsongming/article/details/42234293

 

 

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

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


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

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

下面以聚合数据空气质量城市空气PM2.5指数数据接口为例来演示JSON格式数据的解析。

聚合数据空气质量城市空气PM2.5指数数据接口API文档参见:http://www.juhe.cn/docs/api/id/33/aid/79
JSON返回示例:

 

复制代码
{
    "resultcode": "200",
    "reason": "SUCCESSED!",
    "result": [
        {
            "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" >  
  
        <TextView  
            android: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>  
  
    <Button  
        android:id="@+id/query"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"   
        android:text="查询"   
        android:textSize="23sp" />  
      
    <TextView  
        android: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;  
  
    @Override  
    protected 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);  
            }  
        });  
    }  
  
    @Override  
    public 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 stub  
        super();  
        this.context = context;  
        this.tv_result = tv_result;   
    }  
  
    @Override  
    protected 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 block  
                e.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. 

分享到:
评论

相关推荐

    Android_JSON数据解析

    本篇将详细讲解如何在Android应用中解析JSON数据,主要涉及以下几个方面: 1. JSON基本结构 JSON由两种基本结构构成:对象(Object)和数组(Array)。对象是以花括号 `{}` 包围的键值对集合,键用双引号括起,如`...

    android之json和gson数据解析最完整的代码例子(包括各种样式的json数据)

    JSON(JavaScript Object Notation)和Gson是Android开发中常用的数据序列化和反序列化工具,...以上就是关于“Android之json和gson数据解析最完整的代码例子”的详细介绍,希望对您在学习和使用JSON及Gson时有所帮助。

    Android中Json数据解析

    本教程将深入探讨在Android中如何解析和处理JSON数据。 首先,我们需要理解JSON的基本结构。JSON是一种基于键值对的数据表示方式,主要由对象(Object)和数组(Array)构成。对象用花括号 `{}` 包裹,键值对以冒号...

    android JSON解析数据 android解析天气预报

    笔者近期做到对天气预报JSON数据解析,在此小记。 天气预报接口:http://wthrcdn.etouch.cn/weather_mini?citykey=101200101 JSON数据如下: { desc: OK, status: 1000, data: { wendu: 14, ganmao: 天气...

    android获取页面json格式数据并解析

    最近在整理自己写过的一些应用,发现这个也许对大家有帮助,android通过http页面获取json标准格式数据并且解析其中对象的全过程,其中包含android连接http页面方法,android解析json格式数据方法,json标准化格式...

    老罗android 解析json数据源码

    本教程聚焦于老罗讲解的Android解析JSON数据的源码分析,这对于深入理解JSON处理以及优化应用程序性能至关重要。 首先,我们需要了解JSON的基本结构。JSON是一种基于键值对的格式,数据以键值对的形式存储,如{"key...

    json格式数据解析工具类

    总的来说,这个“json格式数据解析工具类”是Java开发中处理JSON数据的一个利器,它简化了JSON数据的解析过程,让开发者能更专注于业务逻辑,而不是基础的数据转换工作。通过学习和熟练掌握这个工具类的使用,能够...

    android 动态解析获取json数据的键值对

    在Android开发中,有时我们需要从服务器获取JSON数据并解析它以展示在应用中。这个"android 动态解析获取json数据的键值对"的项目就是针对这种情况的一个实例,主要展示了如何在Eclipse环境下,不预先创建JSON键值...

    Android 安卓 json解析

    对于本地JSON文件解析,首先我们需要读取JSON数据。在Android中,这通常通过`AssetManager`类完成,因为JSON文件常存放在`assets`目录下。 ```java try { AssetManager assetManager = getAssets(); InputStream ...

    Android JSON数据的封装及解析

    本教程将深入讲解如何在Android中对JSON数据进行封装和解析,以便于在应用程序中有效使用。 一、JSON基础知识 JSON是一种独立于语言的数据表示格式,它基于ECMAScript的一个子集。一个基本的JSON对象由键值对组成,...

    Android JSON数据格式解析_服务端

    GSON是Google提供的一个Java库,它可以将Java对象转换为等效的JSON字符串,反之亦然,使得Android应用能够轻松地处理JSON数据。本篇文章将详细介绍如何在Android客户端中使用GSON与服务端进行数据交互。 首先,理解...

    android解析json格式数据

    android解析json格式数据代码,代码中有详细的注释,libs包中有需要的第三方类库,直接导入即可使用。包含三种解析json的方式:1.没有实体对象的情况下解析json字符串 2.有实体对象的情况下解析单个json数据 3.有...

    生成JSON格式数据和解析JSON格式数据

    2. **处理数据**:一旦JSON数据被解析成对象,就可以像操作本地数据一样访问和修改它。例如,你可以通过键来获取值: ```javascript console.log(obj.name); // 输出 "John" ``` 在Java中,可以使用`org.json`库来...

    android采用json解析数据的实例

    本实例将详细讲解如何在Android应用中解析JSON数据,主要涉及以下几个关键知识点: 1. JSON基础知识 JSON是一种轻量级的数据交换格式,其结构基于JavaScript语言的对象表示法,但JSON是独立于语言的。基本语法包括...

    Android 实用的数据json数据解析封装类

    本篇文章将详细介绍如何创建一个实用的JSON数据解析封装类,以便快速有效地处理各种形式的JSON数据。 首先,我们需要引入一个JSON库,Android SDK本身包含了org.json库,但为了更强大的功能和更好的性能,推荐使用...

    android解析Json数据

    本篇将深入探讨如何在Android平台上使用org.json库解析JSON数据。 一、JSON基础知识 1. JSON数据结构:主要包括对象(Object)和数组(Array)。对象由键值对组成,用花括号{}包围;数组是一组有序的值,用方括号[]...

    android之JSON数据的构建

    以上就是Android中构建和解析JSON数据的基本步骤。在实际开发中,你可能还需要处理更复杂的JSON结构,包括嵌套的对象和数组,以及使用不同的数据类型。同时,Android还提供了Gson库,它能直接将Java对象转换为JSON...

    Android之Json数据解析

    本文将深入探讨如何在Android中解析JSON数据,包括基本概念、解析方法以及实战示例。 首先,理解JSON的基本结构至关重要。JSON是一种基于文本的格式,由键值对组成,数据以键(key):值(value)的形式表示,值可以...

    android中JSON数据解析

    在Android开发中,JSON...总的来说,Android中的JSON数据解析是通过理解JSON结构,结合`org.json`库或Gson库,以及适当的网络请求库来实现的。合理使用这些工具,能有效地处理和展示从服务器获取的JSON数据。

Global site tag (gtag.js) - Google Analytics