json深度详解及org.json库

简介: 了解json  (Javascript Object Notation) 网站:http://json.org/   english JSON (JavaScript Object Notation) is a lightweight data-interchange format.
  • 了解json  (Javascript Object Notation)

网站:http://json.org/

 

english


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

 

 

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

 

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

 

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

 

 

 

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

 

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

中文翻译


JSON(javascript对象图)是一种轻量级的数交换格式。它易于人类的读与写。易于让机器解析和生成。它基于javascript语言的子集、standard ECMA-262 第三版。JSON是一个独立于变成语言的文本格式,但是呢惯例上被用于我们熟悉的C语系编程语言,比如C,C++,C#,java,javascript,Perl,Python,和其他语言。这些特性使得JSON成为一种理想的数据交换格式语言。



JSON基于两种格式构建:
        1 基于 名/值对儿的集合,在各种语言里实现为一个对象,记录,结构体,指点,哈希表,一个关键列表,或一个关联数组。
         ps:在java中 可以理解为map

        2 一个有序的值列表。在大多数语言里,实现成为一个数组,一个vector,一个列表,或者一个序列。

      这些是一些很常见的数据结构.事实上现代所有的编程语言都以一种或者其他形式支持这种编程结构。这样的意义在于可以基于这样的结构在各种编程语言之间进行交换。


在JSON中,使用以下结构:

一个对象,是一个无需的 名/值对儿。一个对象以花括号 { 开始,以 } 作为结束标志。每个名字后面紧跟 : 冒号,名值对儿之间使用逗号 , 来分割。 





一个数组是一个有序的值集合。一个数组以一个方括号 [ 开始,以右方括号 ] 结束。各个值之间使用逗号 , 进行分割。




一个值,可以使用双引号引起来的字符串、或一个数字、或一个布尔值 true/false、或null、或一个对象object、或者是一个数组array. 并且这些结构是可以被嵌套的。



一个字符串string, 是0或者多个unicode字符构成的,用双引号包起来,用反斜线 \ 进行转义。一个字符被表现为长度为1的字符串(因为javascript中没有字符的概念,只有字符串),而一个字符串则是和C或java语言一样的String类型。







数字非常类似于C或者java语言中的数字类型,除了八进制和十六进制格式在这里没有被用到。

 

json格式中多余的空格都可以被各种语言正确的理解。

比如:

var s={'a':'123','b':false};

var s={'a':'123',      'b':false};//多了一些空格,这样也是合法的。

 

 

javascript中定义的一个对象,就是一种最简单的json格式

如:

var s={'a':'123','b':false,'c':undefined,'d':123,'e':null};

var arr=['a','b','c','d',false];

 

  • JSON不是什么?

json is not a document format  json不是一种文档格式。

json is not a markup language。  json不是一种标记语言

json is not a general serialization  format.  json不是一种通用的可序列化的格式。

-No cyclical/recurring structures.  没有循环的结构

-No invisible structures.  没有不可见的元素

-No functions  没有函数

 

 

  • 对比xml和json

任何的xml数据都可以用json表示出来。

xml json

<users>
    <user gender="male">
        <username>zhangsan</username>
        <password>123</password>
        <age>20</age>
        <address>xi'an</address>
    </user>
    <user gender="fmale">
        <username>zhangsan</username>
        <password>123</password>
        <age>20</age>
        <address>xi'an</address>
    </user>
</users>

var s=[{username:"zhangsan",password:"123",age:20,address:"xi\'an",gender:"male"},{username:"zhangsan",password:"123",age:20,address:"xi\'an",gender:"fmale"}];

 

alert(s[0].address);

 

 

 

  • json值--数字

可以是:  整型、实型、科学技术法。

没有八进制,没有十六进制

没有NaN(Not a Number)且没有infinity(无限大 eg:6/0)------可以使用null代替这NaN和infinity。

 

 

  • json值--字符串

由0或者多个unicode字符组成。

没有”字符”类型,一个字符被表示为一个长度为1 的字符串。

用双引号  "" 括起来

可以用反斜杠 \ 进行转义 

 

  • json值—null

什么都不是的一个值

 

  • json值—对象

Object are unordered containers of key/value pairs.

对象就是一个键/值对儿无序的容器。

对象被花括号 { } 包裹

,  separates key /value pairs  各个键和值对儿用逗号分隔

: separates keys and values   键和值用 冒号分隔

keys are strings   键是字符串

values are JSON values 值时JSON值类型

-struct ,record,hashtable,object  表示结构,记录,hash表,对象

 

  • json值—数组

Arrays are ordered sequences of values . 数组是一个有序的值得集合。

Arrays are wrapped in []. 数组被方括号包裹起来。

, separates values . 用逗号分隔各个值

JSON does not talk about indexing. JSON并不会跟索引打交道。

-An implementation can start array indexing at 0 or 1.

 

javascript通过索引获取数组值

var s=[
    [1,2,3],
    [4,5,6],
    [7,8,9]
    ];
alert(s[0][2]);//3

 

 

 

  • MIME Media Type  媒体类型

application/json
在servlet中 response.setContentType("application/json");,到浏览器端时浏览器就会把数据当做json格式对待。

 

  • JSON中的字符编码

Strictly UNICODE. 严格的unicode编码

 

Default:UTF-8. 默认utf-8编码

 

UTF-16 and UTF-32 are allowed. utf-16和utf-32也是可以的

 

  • JSON处理规则

A JSON decoder must accept all wellformed JSON text.

json解码器必须接受格式良好的json文本。

A JSON decoder may also accept non-JSON text.

json解码器可能接受非json文本(对于有些解码器来说,如果接收非json格式文本就会抛异常)。

A JSON encoder must only produce well-formed JSON text.

一个json编码器必须可以生成格式良好的json文本。

 

  • JSON is the X in Ajax.  json是ajax中的x

ajax 是异步的JavaScript和xml。

而json 的出现,代替了xml。

而ajax人们已经叫习惯了,不好改成ajajson

 

  • JSON data is built into the page. json是内建于页面当中的

<html>
    <script type="text/javascript">
    var data={... JSONdata...};
    </script>
</html>

  • XMLHttpRequest

-Obtain responseText 获得响应文本

-Parse the responseText 解析响应文本

responseData = eval('('+responseText+')');//javascript原生处理

responseData = resonseText.parseJSON();//jquery提供

 

The ability to represent the most general computer science data strutures,records,list,and trees.

json可以表示计算机科学领域大多数的数据结构。如记录,列表,树。

 

  • JSON特点

JSON Doesn’t have namespaces.  json没有命名空间,每个对象都是一个命名空间。

var s={};//s就是一个命名空间

JSON has no validator.  json没有校验器。

JSON is not extensible.  json是不可扩展到的

JSON IS NOT XML.  json不是xml

 

  • XML转JSON练习

xml json
<section> 
    <title>Book-Signing Event</title> 
    <signing> 
        <author title="Mr" name="Vikram Seth"/> 
        <book title="A Suitable Boy" price="$22.95" /> 
    </signing> 
    <signing> 
        <author title="Dr" name="Oliver Sacks"/> 
        <book title="The Island of the Color-Blind" price="$12.95" /> 
    </signing> 
</section>
var s={"section": 
            {"title":"Book-Signing Event", 
             "signing":[ 
                 { 
                    "author":{"title":"Mr","name":"Vikram Seth"}, 
                    "book":{"title":"A Suitable Boy","price":"$22.95"} 
                 },{ 
                    "author":{"title":"Dr","name":"Oliver Sacks"}, 
                    "book":{"title":"The Island of the Color-Blind","price":"$12.95"} 
                 } 
                ] 
            } 
     }; 
            
            alert(s.section.signing[0].author.title);

XML is not a good data interchange format,but it is a document standard.

XML并不是一个理想的数据交换格式(传输的数据量太大,太复杂),但是它是一个文档标准.

 

During the Browser War,innovation was driven by the browser makers.

在浏览器大战时代,进步创新是浏览器厂商决定的。

In the Ajax Age,innvation is being driven by application developers.

在ajax时代,变革是由应用开发则驱动的。

The browser makers are falling behind.

浏览器厂商被甩在后面了。

如果不是firefox的变革思想,IE可能还停留在IE6时代。

 

 

 

 

 

  • 如果用JAVA 和 JavaScript来处理json数据。

  • 使用org.json在java语言中处理json

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

public class Test { 
    public static void main(String[] args) { 
        
        //json对象 
        String jsonContent="{'name':'zhangsan','age':20}"; 
        JSONObject jsonObject=new JSONObject(jsonContent); 
        
        String nameV=jsonObject.getString("name"); 
        int ageV=jsonObject.getInt("age"); 
        
        System.out.println(nameV); 
        System.out.println(ageV); 
        
        System.out.println("-----------------------------"); 
        
        
        //json数组 
        jsonContent="[{'hello':333, 'abc':false, 'xyz':{'a':1, 'b':'ab'}},{'hello':555, 'abc':true, 'xyz':{'a':3, 'b':'ba'}}]"; 
        JSONArray jsonArray=new JSONArray(jsonContent); 
        
        for(int i=0;i<jsonArray.length();i++){ 
            JSONObject jsonObj=jsonArray.getJSONObject(i); 
            int value1=jsonObj.getInt("hello"); 
            boolean value2=jsonObj.getBoolean("abc"); 
            
            JSONObject jsonObj2=jsonObj.getJSONObject("xyz"); 
            int value3=jsonObj2.getInt("a"); 
            String value4=jsonObj2.getString("b"); 
            
            System.out.println(value1); 
            System.out.println(value2); 
            System.out.println(value3); 
            System.out.println(value4); 
        } 
    } 
}

/* 
zhangsan 
20 
----------------------------- 
333 
false 
1 
ab 
555 
true 
3 
ba 
*/

 

 

  • google-gson

http://code.google.com/p/google-gson/

A Java library to convert JSON to Java objects and vice-versa

一个java库,可以将JSON转换成java对象,反之亦然。

english 中文
Gson is a Java library that can be used to convert Java Object into their JSON representation . it can also be used to convert a JSON string to an equivalent Java object . Gson can work with arbitary Java objects including pre-existing objects that you do not have source-code of.

There are a few open-source projects that can convert Java objects to JSON,Howerer,most of them request that you place JAVA annotations in your classes something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very import design goals.

Gson Goals
   Provide simple toJson() and fromJson() methods to convert Java object to JSON and vice-versa

   Allow pre-existing unmodifiable objects to be converted to and from JSON 

   Extensive support of Java Generics

Allow custom representations for objects

   Support arbitraily complex objects (with deep inheritance hierarchies and extensive use of generic types)

Gson是一个java库,可以用于将java对象转换成它的JSON表现形式。它也可以用于将JSON字符串转换成与之对应的Java对象。Gson可以和任意的Java对象搭配使用,包括已经存在的你没法得到源代码的对象。



有一些开源的项目可以将java对象转换成JSON,然而,这些项目大多数需要拟在class中放置注解(注解特点:  必须拥有源代码才能加注解),如果你没有办法获取源代码时就无能为力了。 大多数没有完全支持的Java范型。Gson考虑到这两点的重要性,并将这两点作为主要的设计目标。



Gson 目标
    提供简单的方法 toJson() 和 fromJson()来将java对象转换成JSON,反之亦然。

    允许已经存在的,不能被修改的对象被转换成JSON。(不修改原有类的源代码就可以把他们转换成JSON)


    提供对java泛型强大的支持。

    允许对象的客户化的表现形式。
     支持任意复杂的对象(即使是有很深层次的继承,以及大量使用了泛型类别的对象都可以处理)

一个解析json的库叫 json-path,百度的云推送提供的java服务器sdk中就在使用 json-path

  http://www.oschina.net/code/snippet_273576_34427

 

开始做,坚持做,重复做
相关文章
|
29天前
|
存储 JSON 安全
【C++ JSON库 json值的创建手段】深入探究C++中JSON对象定位与操作:从引用到回调函数
【C++ JSON库 json值的创建手段】深入探究C++中JSON对象定位与操作:从引用到回调函数
62 0
|
7月前
|
JSON 数据格式 Python
Python的json库常用方法
Python的json库常用方法
106 0
|
1月前
|
存储 JSON 算法
C++ JSON库 nlohmann::basic_json::boolean_t 的用法
C++ JSON库 nlohmann::basic_json::boolean_t 的用法
35 0
|
7天前
|
JSON API 数据格式
python的request库如何拿到json的返回值
python的request库如何拿到json的返回值
9 0
|
29天前
|
JSON JavaScript 数据格式
【深入探究C++ JSON库】解析JSON元素的层级管理与遍历手段
【深入探究C++ JSON库】解析JSON元素的层级管理与遍历手段
87 2
|
29天前
|
XML JSON API
深入解析C++ JSON库:nlohmann::json:: parse的内部机制与应用
深入解析C++ JSON库:nlohmann::json:: parse的内部机制与应用
47 0
|
1月前
|
存储 JSON 算法
C++ JSON库 nlohmann::basic_json::binary_t的用法
C++ JSON库 nlohmann::basic_json::binary_t的用法
25 0
|
1月前
|
JSON 数据格式 C++
C++ JSON库 nlohmann::basic_json::binary 的用法
C++ JSON库 nlohmann::basic_json::binary 的用法
24 0
|
1月前
|
JSON 数据格式 C++
C++ JSON库 nlohmann::basic_json::begin() 的用法
C++ JSON库 nlohmann::basic_json::begin() 的用法
22 0
|
1月前
|
JSON 数据格式 C++
C++ JSON库 nlohmann::basic_json::array 的用法
C++ JSON库 nlohmann::basic_json::array 的用法
29 1