json解析总结

来源:互联网 发布:数据透视表数据更新 编辑:程序博客网 时间:2024/06/07 01:13

本文整理自:http://www.open-open.com/lib/view/open1326376799874.html
一、JSON的定义
JSON是一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为
二、JSON 与XML
1.JSON和XML的数据可读性基本相同
2.JSON和XML同样拥有丰富的解析手段
3.JSON相对于XML来讲,数据的体积小
4.JSON与JavaScript的交互更加方便
5.JSON对数据的描述性比XML较差
6.JSON的速度要远远快于XML
关于json的更多内容请访问的官网http://www.json.org/
三、android2.3提供的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中用到的异常
四、使用JSONObject与JSONArray来构建json文本
实例1
void startBuildJsonTextDemo()
{
/*
假设现在要创建这样一个json文本
{ “phone” : [“12345678”, “87654321”,”02887188812”],
“name” : “yuanzhifei89”,
“age” : 100, “address” : { “country” :
“china”, “province” : “jiangsu” },
“married” : false }
*/
try
{
/* 首先最外层是{},是创建一个对象*/
JSONObject person = new JSONObject();
/* 第一个键phone的值是数组,所以需要创建数组对象*/
JSONArray phone = new JSONArray();
phone.put(“12345678”).put(“87654321”);
phone.put(“02887188812”);
person.put(“phone”, phone);

            person.put("name", "yuanzhifei89");            person.put("age", 100);            /* 键address的值是对象,所以又要创建一个对象*/            JSONObject address = new JSONObject();            address.put("country", "china");            address.put("province", "jiangsu");            person.put("address", address);            person.put("married", false);            Log.i(tag,person.toString());        } catch (JSONException ex)        {            /*键为null或使用json不支持的数字格式(NaN, infinities)*/            throw new RuntimeException(ex);        }    }运行结果03-28 21:32:51.095: I/robin(9617): {"phone":["12345678","87654321","02887188812"],"married":false,"address":{"province":"jiangsu","country":"china"},"age":100,"name":"yuanzhifei89"}

五、使用JSONStringer来构建json文本
除了JSONObject与JSONArray两个类,还可以使用JSONStringer来构建json文本
实例2
void startBuildJsonTextDemo2(){
try {
JSONStringer jsonText = new JSONStringer();
/* 首先是{,对象开始。object和endObject必须配对使用 */
jsonText.object();

            jsonText.key("phone");              /* 键phone的值是数组。array和endArray必须配对使用 */             jsonText.array();              jsonText.value("12345678").value("87654321");              jsonText.value("02887188812");            jsonText.endArray();              jsonText.key("name");              jsonText.value("yuanzhifei89");              jsonText.key("age");              jsonText.value(100);              jsonText.key("address");              /* 键address的值是对象  */            jsonText.object();              jsonText.key("country");              jsonText.value("china");              jsonText.key("province");              jsonText.value("jiangsu");              jsonText.endObject();              jsonText.key("married");              jsonText.value(false);              /* },对象结束  */            jsonText.endObject();              Log.i(tag,jsonText.toString());        } catch (JSONException ex) {              throw new RuntimeException(ex);          }      }运行结果03-28 21:41:50.221: I/robin(10153): {"phone":["12345678","87654321","02887188812"],"name":"yuanzhifei89","age":100,"address":{"country":"china","province":"jiangsu"},"married":false}

六、通过JSONObject与JSONArray来解析json
我们可以通过JSONObject与JSONArray的getInt,getString,getDouble,getJSONArray,getJSONObject等函数来解析json.
以下是一个通过网络取得json文本,然后解析的示例。
示例3
public AppGuessResponse getAppListFromHttp(Context mContext)
{
String url = “http://10.158.166.110:8080/AndroidServer/JsonServlet“;
AppGuessResponse res = new AppGuessResponse();
try
{
HttpReturn ret = getDataFromHttp(url);
if (ret.getCode() == HttpStatus.SC_OK)
{
res.parseFrom(ret.getBody());
}
} catch (Exception e)
{
Log.e(tag, “”, e);
}
return res;
}
public HttpReturn getDataFromHttp(String url)
{
/* HttpGet对象*/
HttpGet httpRequest = new HttpGet(url);
int code = -1;
try
{
/* HttpClient对象*/
HttpClient httpClient = new DefaultHttpClient();
/* 获得HttpResponse对象*/
HttpResponse httpResponse = httpClient.execute(httpRequest);
code = httpResponse.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_OK)
{
// 取得返回的数据
byte bytes[] = EntityUtils
.toByteArray(httpResponse.getEntity());
return new BaseHttpReturn(code, bytes);
} else
{
return new BaseHttpReturn(code);
}
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return new BaseHttpReturn(code);
}
interface HttpReturn
{
int getCode();

    byte[] getBody();}class BaseHttpReturn implements HttpReturn{    final int code;    final byte body[];    BaseHttpReturn(int code)    {        this.code = code;        this.body = null;    }    BaseHttpReturn(int code, byte bytes[])    {        this.code = code;        this.body = bytes;    }    @Override    public int getCode()    {        // TODO Auto-generated method stub        return 0;    }    @Override    public byte[] getBody()    {        // TODO Auto-generated method stub        return null;    }}interface ResponseParse{    public void parseFrom(byte[] bytes);    public void parseFrom(String str);}class Application{    String name;    String packageName;    String version;    int versionCode;    double price;    long size;    long downloadCount;    public long getDownloadCount()    {        return downloadCount;    }    public void setDownloadCount(long downloadCount)    {        this.downloadCount = downloadCount;    }    public long getSize()    {        return size;    }    public void setSize(long size)    {        this.size = size;    }    public String getName()    {        return name;    }    public void setName(String name)    {        this.name = name;    }    public String getPackageName()    {        return packageName;    }    public void setPackageName(String packageName)    {        this.packageName = packageName;    }    public String getVersion()    {        return version;    }    public void setVersion(String version)    {        this.version = version;    }    public int getVersionCode()    {        return versionCode;    }    public void setVersionCode(int versionCode)    {        this.versionCode = versionCode;    }    public double getPrice()    {        return price;    }    public void setPrice(double price)    {        this.price = price;    }}class AppGuessResponse implements ResponseParse{    private List<Application> mApplications = new ArrayList<Application>();    private boolean mIsFinish = false;    private boolean mIsSuccess = false;    private int allCount = 0;    private Date expireDate = new Date(System.currentTimeMillis() + 24 * 60            * 60 * 1000);    public Date getExpireDate()    {        return expireDate;    }    public void setExpireDate(Date expireDate)    {        this.expireDate = expireDate;    }    public int getAllCount()    {        return allCount;    }    public void setAllCount(int allCount)    {        this.allCount = allCount;    }    public boolean getIsSuccess()    {        return mIsSuccess;    }    public Application getApplicationItem(int i)    {        return mApplications.get(i);    }    public int getApplicationItemCount()    {        return mApplications.size();    }    public List<Application> getApplicationItemList()    {        return mApplications;    }    public boolean isFinish()    {        return mIsFinish;    }    @Override    public void parseFrom(byte[] bytes)    {        // TODO Auto-generated method stub    }    @Override    public void parseFrom(String strJson)    {        try        {            JSONObject jsonObject = new JSONObject(strJson);            if (jsonObject.has("endpage"))            {                mIsFinish = jsonObject.getInt("endpage") == 0 ? true : false;            } else            {                mIsFinish = false;            }            if (jsonObject.has("allcount"))            {                allCount = jsonObject.getInt("allcount");            }            if (jsonObject.has("list"))            {                JSONArray jsonArray = jsonObject.getJSONArray("list");                if (jsonArray.length() != 0)                {                    for (int i = 0; i < jsonArray.length(); i++)                    {                        JSONObject jsonObject2 = jsonArray.getJSONObject(i);                        Application app = new Application();                        app.setName(jsonObject2.getString("name"));                        app.setPackageName(jsonObject2.getString("packageName"));                        app.setSize(jsonObject2.getLong("size"));                        app.setPrice(jsonObject2.optDouble("price", 0.0));                        app.setVersion(jsonObject2.getString("version"));                        app.setVersionCode(jsonObject2.getInt("versioncode"));                        if (jsonObject2.has("downloadCount"))                        {                            app.setDownloadCount(jsonObject2.optLong(                                    "downloadCount", 0));                        }                        mApplications.add(app);                    }                }            }            mIsSuccess = true;        } catch (JSONException e)        {            mIsSuccess = false;        }    }

七、通过JSONTokener来解析json文本
7.1、将json文本解析为对象
我们可以通过JSONTokener的nextValue()来获得JSONObject对象,然后再通过JSONObject对象来做进一步的解析。
实例4
void startJSONTokenerDemo(){
final String JSON =
“{” +
” \”phone\” : [\”12345678\”, \”87654321\”],” +
” \”name\” : \”yuanzhifei89\”,” +
” \”age\” : 100,” +
” \”address\” : { \”country\” : \”china\”, \”province\” : \”jiangsu\” },” +
” \”married\” : false,” +
“}”;

                try {                      JSONTokener jsonTokener = new JSONTokener(JSON);                      /* 此时还未读取任何json文本,直接读取就是一个JSONObject对象。                                                       如果此时的读取位置在"name" : 了,那么nextValue就是"yuanzhifei89"(String)                      */                    JSONObject person = (JSONObject) jsonTokener.nextValue();                      /* 接下来的就是JSON对象的操作了 */                     person.getJSONArray("phone");                      person.getString("name");                      person.getInt("age");                      person.getJSONObject("address");                      person.getBoolean("married");                  } catch (JSONException ex) {                      /*异常处理代码  */                }        }

7.2、将json文本解析为文本
我们可以通过JSONTokener的一些方法将json文本解析为文本
实例5
void startJSONTokenerDemo2(){
final String JSON =
“{” +
” \”phone\” : [\”12345678\”, \”87654321\”],” +
” \”name\” : \”yuanzhifei89\”,” +
” \”age\” : 100,” +
” \”address\” : { \”country\” : \”china\”, \”province\” : \”jiangsu\” },” +
” \”married\” : false,” +
“}”;

        try {              JSONTokener jsonTokener = new JSONTokener(JSON);              /* 继续向下读json文本中的8个字符。此时刚开始,即在{处  */            Log.i(tag,"jsonTokener.next(8)|"+jsonTokener.next(8));            /* 继续向下读json文本中的1个字符  */            Log.i(tag,"jsonTokener.next()|"+jsonTokener.next());            /* 继续向下读取一个json文本中的字符。该字符不是空白、同时也不是注释中的字符  */            Log.i(tag,"jjsonTokener.nextClean()|"+jsonTokener.nextClean());             /* 返回当前的读取位置到第一次遇到'a'之间的字符串(不包括a)。  */            Log.i(tag,"jsonTokener.nextString('a')|"+jsonTokener.nextString('a'));            /* 返回当前读取位置到第一次遇到字符串中(如"0089")任意字符之间的字符串,同时该字符是trimmed的。(此处就是第一次遇到了89)*/              Log.i(tag,"jsonTokener.nextTo(\"0089\")|"+jsonTokener.nextTo("0089") );            /* 读取位置回退一个  */            jsonTokener.back();             Log.i(tag,"jsonTokener.back()");            Log.i(tag,"jsonTokener.next()|"+jsonTokener.next());            /* 读取位置前进到指定字符串处(包括字符串)*/              jsonTokener.skipPast("address");             Log.i(tag,"skipPast(\"address\")");            Log.i(tag,"jsonTokener.next(8)|"+jsonTokener.next(8));            /* 读取位置前进到执行字符处(不包括字符)  */            Log.i(tag,"jsonTokener.skipTo('m')|"+jsonTokener.skipTo('m'));            jsonTokener.next(8);             Log.i(tag,"jsonTokener.next(8)|"+jsonTokener.next(8));          } catch (JSONException ex) {              // 异常处理代码          }      }运行结果:03-28 22:05:03.800: I/robin(10412): jsonTokener.next(8)|{   "pho03-28 22:05:03.800: I/robin(10412): jsonTokener.next()|n03-28 22:05:03.800: I/robin(10412): jjsonTokener.nextClean()|e03-28 22:05:03.800: I/robin(10412): jsonTokener.nextString('a')|" : ["12345678", "87654321"],   "n03-28 22:05:03.800: I/robin(10412): jsonTokener.nextTo("0089")|me" : "yuanzhifei03-28 22:05:03.800: I/robin(10412): jsonTokener.back()03-28 22:05:03.800: I/robin(10412): jsonTokener.next()|i03-28 22:05:03.800: I/robin(10412): skipPast("address")03-28 22:05:03.800: I/robin(10412): jsonTokener.next(8)|" : { "c03-28 22:05:03.800: I/robin(10412): jsonTokener.skipTo('m')|m03-28 22:05:03.810: I/robin(10412): jsonTokener.next(8)| : false

八、JsonReader
原文:http://tonysun3544.iteye.com/blog/1330027
在google android中也有关于解析JSON的类库:java.io.JsonReader,但是只能在3.0以后的版本中才可以用,在这里我们用google提供的类库google-gson,可以从code.google.com/p/google-gson/下载jar包。
下面通过一个小例子来学习一下:
例子:
[{“name”:”zhangsan”,”age”:22},{“name”:”lisi”,”age”:23}]
分析:
1.开始解析数组
2.开始解析对象
3.解析键值对
4.解析键值对
5.解析对象结束
6.开始解析对象
7.解析键值对
8.解析键值对
9.解析对象结束
10.解析数组结束
示例8
void startJsonReaderDemo(){
private String jsonData = “[{\”name\”:\”zhangsan\”,\”age\”:22},{\”name\”:\”lisi\”,\”age\”:23}]”;
JsonReader reader = new JsonReader(new StringReader(jsonData));
try
{
reader.beginArray(); /* 开始解析数组 */
while (reader.hasNext())
{
reader.beginObject(); /* 开始解析对象 */
while (reader.hasNext())
{
String tagName = reader.nextName(); /* 得到键值对中的key */
/* key为name时/*
if (tagName.equals(“name”))
{
Log.i(tag, “name———>” + reader.nextString()); /* 得到key中的内容 */
} else if (tagName.equals(“age”))/* key为age时*/
{
Log.i(tag, “age———>” + reader.nextInt()); /* 得到key中的内容 */
}
}
reader.endObject();
}
reader.endArray();
} catch (IOException e)
{
e.printStackTrace();
}
}

0 0