---
title: "JSON入门——JSON的组成和解析"
author: "deepnighttwo"
date: "2011-10-10T15:43:27Z"
tags: []
categories: ["编程语言"]
slug: "json-json"
draft: false
lastmod: "2011-10-10T15:43:27Z"
id: 1188769
url: "https://deepnighttwo.iteye.com/blog/1188769"
---

用JSON也有挺长时间了，最近做了个小软件，需要调用第三方API。Google translate API是使用JSON数据格式的。而douban API是使用XML数据格式的。过程中不禁感慨，xml真是不大适合存储数据，占用资源多不说，解析起来也很麻烦。现在越来越多的api开始使用json 作为数据载体，还是有它的道理的。facebook最新的的graph api也是使用json作为数据载体。

相比之下json就简单多了。关于json的介绍可以参考官方文档[http://www.json.org/json-zh.html](http://www.json.org/json-zh.html) 。json是如此的简单，1）以至于解析的时候只需要两个类，2）甚至json的解析包都不是以jar包的形式发布，而是直接以源代码的形式发布，3）解析只需要Java基础的类库，不需要第三方类库。这三点任何一点都足以让任何一个xml解析器泪奔……

使用json之前要先去[http://www.json.org/java/index.html](http://www.json.org/java/index.html) 这里下载支持包（源代码，就一个package，直接拷贝到项目里即可）。与json解析相关的类就只有JSONObject和JSONArray，剩下的几个类好像是帮助生产json的。也许json也是考虑到用户需要修改这几个类的内容，所以没有打包成jar发布吧。

json的格式可以通过最开始给出的文档有个大概的认识。json的log很传神，json就是这么一种可以无限嵌套的格式。下面是一个简单的程序，实地的使用以下json。

程序中需要解析的json是：

{

  "strValue":"here is str value",

   "nullValue":null,"intvalue":999,

   "doublevalue":999,

   "booleanValue":true,

   "array":["a1", "a2", true, 2, 33.3, null,

       { "innerStr":"here is a inner str", "innerInteger":123456789},

        \["Hi, found me ?"]],

   "innerOBJ":{"innerStr":"here is a inner str", "innerInteger":123456789}

}

这段json涵盖了尽量多了json中的格式，包括键值对，数组，数组中的数组，数组中的JSONObject，boolean值，double值，integer值。解析的代码如下：

[view source](http://www.cnblogs.com/deepnighttwo/archive/2011/02/28/1967008.html#viewSource "view source") [print](http://www.cnblogs.com/deepnighttwo/archive/2011/02/28/1967008.html#printSource "print") [?](http://www.cnblogs.com/deepnighttwo/archive/2011/02/28/1967008.html#about "?")

`01` `package` `org.json.learn;`

`02` `import` `org.json.JSONException;`

`03` `import` `org.json.JSONObject;`

`04`  

`05` `public` `class` `JSONObjectUseApp {`

`06`  

`07` `    ` `/**`

`08` `     ` `* @param args`

`09` `     ` `* @throws JSONException`

`10` `     ` `*/`

`11` `    ` `public` `static` `void` `main(String[] args)` `throws` `JSONException {`

`12` `        ` `String jsonStr =` `"{\"strValue\":\"here is str value\", "`

`13` `                ` `+` `"\"nullValue\":null,"`

`14` `                ` `+` `"\"intvalue\":999, "`

`15` `                ` `+` `"\"doublevalue\":999, "`

`16` `                ` `+` `"\"booleanValue\":true, "`

`17` `                ` `+` `"\"array\":[\"a1\",\"a2\",true, 2, 33.3, null,"`

`18` `                ` `+` `"{\"innerStr\":\"here is a inner str\", \"innerInteger\":123456789}, "`

`19` `                ` `+` `"[\"Hi, found me ?\"]"`

`20` `                ` `+` `"], "`

`21` `                ` `+` `"\"innerOBJ\":{\"innerStr\":\"here is a inner str\", \"innerInteger\":123456789}}"` `;`

`22` `        ` `log(jsonStr);`

`23` `        ` `JSONObject json =` `new` `JSONObject(jsonStr);`

`24` `        ` `log(` `"String from JSON\t"` `+ json.getString(` `"strValue"` `));`

`25` `        ` `log(` `"Null from JSON\t"` `+ json.get(` `"nullValue"` `));`

`26` `        ` `log(` `"Integer from JSON\t"` `+ json.getInt(` `"intvalue"` `));`

`27` `        ` `log(` `"Double from JSON\t"` `+ json.getDouble(` `"doublevalue"` `));`

`28` `        ` `log(` `"Boolean from JSON\t"` `+ json.getBoolean(` `"booleanValue"` `));`

`29`  

`30` `        ` `log(` `"String from JSON Array\t"`

`31` `                ` `+ json.getJSONArray(` `"array"` `).getString(` `0` `));`

`32`  

`33` `        ` `log(` `"String from inner JSON Object \t"`

`34` `                ` `+ json.getJSONObject(` `"innerOBJ"` `).getString(` `"innerStr"` `));`

`35`  

`36` `        ` `log(` `"Int from JSONArray from JSON Object \t"`

`37` `                ` `+ json.getJSONArray(` `"array"` `).getJSONObject(` `6` `)`

`38` `                        ` `.getInt(` `"innerInteger"` `));`

`39`  

`40` `        ` `log(` `"Int from JSON Array from JSON Array \t"`

`41` `                ` `+ json.getJSONArray(` `"array"` `).getJSONArray(` `7` `).getString(` `0` `));`

`42` `    ` `}`

`43`  

`44` `    ` `private` `static` `void` `log(Object obj) {`

`45` `        ` `System.out.println(obj.toString());`

`46` `    ` `}`

`47` `}`

JSONObject是一对大括号中的内容，里面都是键值对，取值的时候根据key取出value的值。key必须是string，必须被双引号括 住，后面是个冒号，紧跟着是值。值可以是string，int，boolean，integer，double这些基础值，也可以是另一个 JSONObject或者一个JSONArray。**JSONArray里的value也可以是任意value，但是是没有key的，所以只能根据索引取值。** JSONObject和JSONArray这些都可以互相嵌套。

我觉得使用json来表示数据简直就是轻松愉快。Google推的ProtoBuffer可以说就是另一种加强型的JSON。对于json来说，其 内容还是需要解析一下的，ProtoBuffer则允许用户定义schema来指定数据的格式，然后编译后生成相应的类。类中包含了数据绑 定，serialization和deserialization等操作。可以说数据格式着一层对于用户来说就彻底通明了。而且这个格式小，快。