解析JSON的过程

来源:互联网 发布:sql server 2015 64位 编辑:程序博客网 时间:2024/05/05 16:46
什么是JSON
官网的解释是JSON (JavaScript Object Notation) is a lightweight data-interchange format 。

JSON的格式
键值对的集合 {k:v}
值得有序列表 [1,2]

什么是JSON-java
JSON官网提供的java语言处理json数据的小框架。
阅读该源码的目的
1、学习解析类工具的原理
2、锻炼读代码的能力

解析JSON的原理
1、JSON-java最重要的类有三个。
JSONObject : 包装一个map。 用来表示一个{k:v,k2:v2,k3:[1,2]}形式的json数据
JSONArray :包装一个ArrayList。用来表示一个[1,2,{k:v}]形式的json数据
JSONTokener:包装一个Reader。用来存储、读取、操作一个表示JSON数据的字符串

2、原理

1、JSONObject和JSONArray都可以用一个JSONTokener作为构造参数去实例化。
2、解析时可能会产生多个JSONObject或者JSONArray。但是他们都是操作同一个JSONTokener。
3、JSONObject和JSONArray可以分别通过JSONTokener提供的方法解析出对方。可以实现嵌套。
例子
new JSONObject("{k:v,k2:v2,k3:[1,{k4:V4}]}");
解析出{
           解析出k和v存入map
           解析出k2和v2存入map
           解析出k3 然后发现一个数组的左标记[
                     new  JSONArray 开始解析[1,{k4:V4}]}
                     解析出[
                     解析出1 放入list
                     解析出json对象的左标记{
                               new JSONObject 开始解析 {k4:V4}]}
                               解析出k4和v4放入map
                     发现}一个JSONObject解析结束
                    解析出 {k4:V4} 放入list。
                    发现 ] 一个JSONArray解析结束
           解析出[1,{k4:V4}] 和k3 一起放入map (第一个JSONObject)。
           解析出} 

全部解析结束。


在Java中解析与构造JSON

        在www.json.org上公布了很多Java下的json解析工具,其中org.json和json-lib比较简单,两者使用上差不多。下面两段源代码是分别使用这两个工具解析和构造JSON的演示程序。

这是使用json-lib的程序:
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
String json = "{\"name\":\"reiz\"}";
JSONObject jsonObj = JSONObject.fromObject(json);
String name = jsonObj.getString("name");
jsonObj.put("initial", name.substring(0, 1).toUpperCase());
String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" };
jsonObj.put("likes", likes);
Map<String, String> ingredients = new HashMap<String, String>();
ingredients.put("apples", "3kg");

ingredients.put("sugar", "1kg");
ingredients.put("pastry", "2.4kg");
ingredients.put("bestEaten", "outdoors");
jsonObj.put("ingredients",ingredients);
System.out.println(jsonObj);
}
}

这是使用org.json的程序:
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

public class Test {
public static void main(String[] args) throws JSONException {
String json = "{\"name\":\"reiz\"}";
JSONObject jsonObj = new JSONObject(json);
String name = jsonObj.getString("name");

jsonObj.put("initial", name.substring(0, 1).toUpperCase());
String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" };
jsonObj.put("likes", likes);
Map<String, String> ingredients = new HashMap<String, String>();
ingredients.put("apples", "3kg");

ingredients.put("sugar", "1kg");
ingredients.put("pastry", "2.4kg");
ingredients.put("bestEaten", "outdoors");
jsonObj.put("ingredients", ingredients);
System.out.println(jsonObj);
}
}
两者的使用几乎是相同的,但org.json比json-lib要轻量得多,前者没有任何依赖,而后者要依赖ezmorph和commons的lang、logging、beanutils、collections等组件。


附一个应用例子:

// 解析搜索的结果 
public Object searchedDataAnalysis(byte[] all) {
        Vector<Map<String, String>> vector = new Vector<Map<String, String>>();
        try {
            String str = new String(all, "UTF-8");
            Log.v("SearchedDataAnalysis start...\n", str);

            if (str.length() != 0) {
                JSONObject jsObj = new JSONObject(str);
                if (jsObj.has(TOTAL_NUM)){
                    setTotalNum(Integer.parseInt(jsObj.getString(TOTAL_NUM)));
                }
                if (jsObj.has(ITEMS_ARRAY)) {
                    JSONArray array = jsObj.getJSONArray(ITEMS_ARRAY);
                    // 如果搜说列表为0
                    if (array.length() == 0) {
                        Apphandler.sendEmptyMessage(SEARCHEDITEM_IS_NULL);
                        return null;
                    }
                    for (int i = 0; i < array.length() && i < pageSize; i++) {
                        JSONObject item = array.getJSONObject(i);

                        Map<String, String> data = new HashMap<String, String>();
                        // 标题
                        if (item.has(PRD_TITLE)) {
                            String title = item.getString(PRD_TITLE);
                            title = title.replaceAll("\r\n", " ");
                            title = title.replaceAll("\n", " ");
                            title = title.replaceAll("\r", " ");
                            data.put(PRD_TITLE, title);
                        }
                        // 价格
                        if (item.has(PRD_PRICE))
                            data.put(PRD_PRICE, item.getString(PRD_PRICE));
                        // 图片地址
                        if (item.has(PRD_PICURL))
                            data.put(PRD_PICURL, item.getString(PRD_PICURL));
                        // 区域
                        if (item.has(PRD_AREA))
                            data.put(PRD_AREA, item.getString(PRD_AREA));
                        // 售出数
                        if (item.has(PRD_SELLED))
                            data.put(PRD_SELLED, item.getString(PRD_SELLED));
                        // // 信誉
                        if (item.has(PRD_CREDIT))
                            data.put(PRD_CREDIT, item.getString(PRD_CREDIT));
                        if (item.has(PRD_USER_TYPE))
                            data.put(PRD_USER_TYPE,
                                    item.getString(PRD_USER_TYPE));
                        if (item.has(PRD_DETAIL_URL))
                            data.put(PRD_DETAIL_URL,
                                    item.getString(PRD_DETAIL_URL));
                        // 商品ID
                        if (item.has(ITEM_ID))
                            data.put(ITEM_ID, item.getString(ITEM_ID));
                        vector.add(data);
                    }
                    addCurrentPage(1);
                } else {
                    vector = null;
                }
            } else {
                vector = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            vector = null;
        }
        return vector;
    }

原创粉丝点击