Android解析json数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a249900679/article/details/51195505

JSON是一种轻量级的数据交换格式。 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)

 

先来看看json的语法:

1、JSON 语法规则

JSON 语法是 JavaScript 对象表示语法的子集。

·            数据在键值对中

·            数据由逗号分隔

·            花括号保存对象

·            方括号保存数组

2、JSON 名称/值对

JSON 数据的书写格式是:名称/值对。

名称/值对组合中的名称写在前面(在双引号中),值对写在后面(同样在双引号中),中间用冒号隔开:"key":"value"

3、JSON

JSON 值可以是:

·            数字整数浮点数

·            字符串(在双引号中)

·            逻辑值true false

·            数组(在方括号中)

·            对象(在花括号中)

·            null

以下来讲讲json的几种格式:

1.      键-值:{“key”:”value”}

2.      表示数组:{[{“key11”:”value11”, “key12”:”value12”},{“key21”:”value21”},{“key31”:”value31”}]}

3.      数组中有数组:{[[{“key111”:”value111”, “key112”:”value112”, “key113”:”value113”},{“key121”:”value121”},{“key131”:”value131”}],[{“key211”:”value211”},{“key221”:”value221”},{“key231”:”value231”}],[{“key311”:”value311”}]]}

我暂时用到的就是这三种形式的json,所以接下来将的android解析json数据就以这三种方式为例子,如果用到其他形式的,相信根据以下方法,可以推写出解析其他形式的json数据的方法。

1、首先第一种比较简单,只是单独的json数据:

所以返回的只是一维数组。

先把json形式的字符串封装成JSONObject对象

JSONObject jsonObject = new JSONObject(Value);

取出key

Iterator<?> keys = jsonObject.keys();

因为取出的key是乱序的,所以需要给它排序,方便使用(用到时就知道了)

List<String> keyList = newArrayList<String>();

while (keys.hasNext()) {

    String key = (String) keys.next();

    keyList.add(key);

}

Collections.sort(keyList);

我是按字典序升序排列,不懂字典序的可自行百度。。这里就不做讲解了

Len为json数据长度

int len = jsonObject.length();

result存取出来的值

String[] result = new String[len];

int i = 0;

根据key取出值

while (!keyList.isEmpty()) {

    String key = keyList.get(0);

    第一次用时,把可以打印出来,保存起来,用到时,可根据key的顺序取出对应的值

    这样不会直接把key暴露出来

    Log.d("key", key + "---->" + i);

    result[i++] = jsonObject.getString(key);

    keyList.remove(0);

}

例如:{“user_id”:”1”,”user_name”:”小熊”,”email”:”xxx”}

则取出来的key顺序为email,user_id,user_name;

然后根据key取出来的值,即result[3] = {“xxx”, “1”, “小熊”};

2、接下来是json数组,返回的是二维数组,第一层表示有多少json数据,第二层表示各层json数据中有多少内容

同样,把json数组形式的value封装成JSONArray对象

JSONArray jsonArray = newJSONArray(Value);

定义一个二维数组,第一层长度为jsonArray的长度,即有多少json数据,第二层不确定,暂时不用给定长度

String[][] result = newString[jsonArray.length()][];

接下来的就有点区别,先遍历jsonArray:

for (int i = 0; i < jsonArray.length(); ++i) {

    再把jsonArray中的每一项封装成JSONObject对象

    JSONObject jsonObject = (JSONObject) jsonArray.opt(i);

    len为jsonObject的长度,即第二层的长度

    int len = jsonObject.length();

    result[i] = new String[len];

    int j = 0;

    接下来的方法就跟上面的json数据解析的方法一样

    Iterator<?> keys = jsonObject.keys();

    List<String> keyList = new ArrayList<String>();

    while (keys.hasNext()) {

        String key = (String)keys.next();

        keyList.add(key);

    }

    Collections.sort(keyList);

    while (!keyList.isEmpty()) {

        String key =keyList.get(0);

        Log.d("key" + i, key + "---->" + j);

        result[i][j++] =jsonObject.getString(key);

       keyList.remove(0);

    }

}

例如:{[{“user_id”:”1”,”user_name”:”小熊”},{“school”:”华软”},{“book1”:”Android”,”book2”:”c++”,”book3”:”数据结构与算法”}]}

取出来的key,即result[3] = {{“user_id”,”user_name”},{“school”},{“book1”,”book2”,”book3”}}

然后根据key取出来的值为

Result[0] = {“1”,”小熊”}

Result[1] = {“华软”}

Result[2] = {“Android”,”c++”,”数据结构与算法”}

 

3、最后一种为数组中带数组的形式,返回的是三维数组

第一层表示有多少个数组,第二层表示每个数组中有多少数组,第三层表示每个数组中有多少内容,说起来比较模糊,先来看看代码:

 

跟第二种一样,先封装成JSONArray对象

JSONArray jsonArrayTwo = new JSONArray(Value);

定义一个三维数组,第一层为jsonArrayTwo长度,即有多少个数组,第二、三层暂时不确定

String[][][] result = newString[jsonArrayTwo.length()][][];

 

for (int i = 0; i < jsonArrayTwo.length(); ++i) {

    遍历第一层,获取第二层的长度,即每个数组中有多少个数组

    JSONArray jsonArray = new JSONArray(jsonArrayTwo.opt(i)

.toString());

    result[i] = new String[jsonArray.length()][];

    for (int j = 0; j < jsonArray.length(); ++j) {

       最后遍历,数组中的内容,方法跟前面两种差不多,就不做多介绍了

        JSONObject jsonObject =(JSONObject) jsonArray.opt(j);

        int len = jsonObject.length();

        result[i][j] = new String[len];

        int k = 0;

        Iterator<?> keys =jsonObject.keys();

        List<String>keyList = new ArrayList<String>();

       while (keys.hasNext()) {

           String key = (String) keys.next();

           keyList.add(key);

       }

       Collections.sort(keyList);

       while (!keyList.isEmpty()) {

           String key = keyList.get(0);

           Log.d("key" + j, key + "---->" + k);

           result[i][j][k++] = jsonObject.getString(key);

           keyList.remove(0);

       }

    }

例如:{[[{“user_id”:”1”,”user_number”:”14401”,“user_name”:”小熊”}],[{“like”:”1”}],[{“goods_id”:”2”,”goods_name”:”手机”,“goods_price”:”1999”},{“goods_cou”:”100”}]]}

最终取出来的数据为

Result[0][1] = {“1”, “小熊”, “14401”}

Result[0][2] = {“1”}

Result[0][3] = {“100”, “2”, “手机”, “1999”}

 

下面是完整的代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

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

import android.util.Log;

public class AnalysisJSON {

	/**
	 * 
	 * @Title: getResultByJsonArrayTwo
	 * @Description: 解析json数组(数组内容为一维数组)
	 * @example: {[[{},{},{},{}],[{},{}],[{}],[{},{}]]}
	 * @param @param Value
	 * @param @return
	 * @return String[][][]
	 * @throws
	 */
	public String[][][] getResultByJsonArrayTwo(String Value) {

		try {
			JSONArray jsonArrayTwo = new JSONArray(Value);
			String[][][] result = new String[jsonArrayTwo.length()][][];

			for (int i = 0; i < jsonArrayTwo.length(); ++i) {
				JSONArray jsonArray = new JSONArray(jsonArrayTwo.opt(i)
						.toString());
				result[i] = new String[jsonArray.length()][];
				for (int j = 0; j < jsonArray.length(); ++j) {
					JSONObject jsonObject = (JSONObject) jsonArray.opt(j);
					int len = jsonObject.length();
					result[i][j] = new String[len];
					int k = 0;
					Iterator<?> keys = jsonObject.keys();
					List<String> keyList = new ArrayList<String>();

					while (keys.hasNext()) {
						String key = (String) keys.next();
						keyList.add(key);
					}
					Collections.sort(keyList);

					while (!keyList.isEmpty()) {
						String key = keyList.get(0);
						Log.d("key" + j, key + "---->" + k);
						result[i][j][k++] = jsonObject.getString(key);
						keyList.remove(0);
					}
				}
			}
			return result;

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

		return null;
	}

	/**
	 * 
	 * @Title: getResultByJsonArray
	 * @Description: 解析json数组
	 * @example: {[{},{},{},{},{},{},{},{},{}]}
	 * @param @param Value
	 * @param @return
	 * @return String[][]
	 * @throws
	 */
	public String[][] getResultByJsonArray(String Value) {

		try {
			JSONArray jsonArray = new JSONArray(Value);

			String[][] result = new String[jsonArray.length()][];

			for (int i = 0; i < jsonArray.length(); ++i) {
				JSONObject jsonObject = (JSONObject) jsonArray.opt(i);
				int len = jsonObject.length();
				result[i] = new String[len];
				int j = 0;
				Iterator<?> keys = jsonObject.keys();
				List<String> keyList = new ArrayList<String>();

				while (keys.hasNext()) {
					String key = (String) keys.next();
					keyList.add(key);
				}
				Collections.sort(keyList);

				while (!keyList.isEmpty()) {
					String key = keyList.get(0);
					Log.d("key" + i, key + "---->" + j);
					result[i][j++] = jsonObject.getString(key);
					keyList.remove(0);
				}
			}

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

		return null;
	}

	/**
	 * 
	 * @Title: getResultByJson
	 * @Description: 解析json数据
	 * @example: {}
	 * @param @param Value
	 * @param @return
	 * @return String[]
	 * @throws
	 */
	public String[] getResultByJson(String Value) {

		try {
			JSONObject jsonObject = new JSONObject(Value);
			Iterator<?> keys = jsonObject.keys();

			List<String> keyList = new ArrayList<String>();

			while (keys.hasNext()) {
				String key = (String) keys.next();
				keyList.add(key);
			}
			Collections.sort(keyList);

			int len = jsonObject.length();
			String[] result = new String[len];
			int i = 0;

			while (!keyList.isEmpty()) {
				String key = keyList.get(0);
				Log.d("key", key + "---->" + i);
				result[i++] = jsonObject.getString(key);
				keyList.remove(0);
			}

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

		return null;
	}
}




猜你喜欢

转载自blog.csdn.net/a249900679/article/details/51195505
今日推荐