解析JSON数据

来源:互联网 发布:python读txt文件 编辑:程序博客网 时间:2024/06/14 00:49

谷歌提供的GSON开源库大多数人都在用,使用简单方便就不记了。如果GSON不能满足需求,有时候还是需要自己按需求解析的。记一下:

JSONObject用法:android自带,官方提供的

import org.json.JSONObject;//String类型jsonJSONObject obj = new JSONObject(jsonString);//array类型JsonJSONArray jsonArray = new JSONArray(jsonString);            for (int i = 0; i < jsonArray.length(); i++) {                JSONObject obj = jsonArray.getJSONObject(i);                String id = obj.getString("id");            }//很多时候是Sting里包含Array的jsonJSONArray jsonArray =  new JSONObject(jsonString).getJSONArray("List");

FastJSON用法:fastjson-1.1.38.jar

public class JsonParser<T> {    public T parserJsonBean(String jsonString, Class<T> bean) {        try {            org.json.JSONObject obj = new org.json.JSONObject(jsonString);                return JSONObject.parseObject(jsonString, bean);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public List<T> parserJsonList(String jsonString, Class<T> bean) {        try {            org.json.JSONObject obj = new org.json.JSONObject(jsonString);                if (obj.getJSONArray("List") != null) {// obj.has("List")                    return JSONObject.parseArray(obj.getString("List"), bean);            }        } catch (Exception e) {            e.printStackTrace();        }        return null;    }}
原创粉丝点击