zoukankan      html  css  js  c++  java
  • REST 服务与 JSON 格式

    REST(REpresentational State Transfer)Web 是一种轻量级的服务模式,通常用于构建 Web API,例如国外的 Skydrive,Dropbox,Twitter,国内的新浪微博等,都利用这种方式来提供第三方的服务接口。

    REST Web API 经常使用 http 或者 https 传输协议,我们可以看看 Dropbox 的 REST API 的例子:

    GET  https://api.dropbox.com/1/account/info
    GET  https://api.dropbox.com/1/metadata/sandbox/hello.txt
    GET  https://api-content.dropbox.com/1/files/sandbox/hello.txt
    POST https://api-content.dropbox.com/1/files/sandbox/hello.txt
    PUT  https://api-content.dropbox.com/1/files_put/sandbox/hello.txt?param=val

    可以看出,REST API 首先有一些 URI 地址,惟一的对应每一个资源,然后用 GET,POST,PUT 等方法来表示对某个资源读取,创建和修改等操作。

    客户端和服务器之间还需要有确定数据格式,最常用的是 JSON(JavaScript Object Notation)格式。JSON 定义的数据结构是 JavaScript 数据结构的一个子集,容易阅读和编写,在其它语言中也很方便使用。例如:

    {
        "bytes": 0,
        "path": "/Public",
        "is_dir": true,
        "contents": [
            {
                "size": "0 bytes",
                "bytes": 0,
                "path": "/Public/latest.txt",
                "is_dir": false
            },
            {
                "size": "0 bytes",
                "bytes": 0,
                "path": "/Public/history.txt",
                "is_dir": false
            }
        ],
        "revision": 29007
    }
    

    可以看到, JSON 的语法和 JavaScript 的非常类似,需要注意的地方主要有:字符串只能用双引号,而对象的属性名必须用引号包含。

    JavaScript 中的 JSON 对象只有两个方法:JSON.parse 和 JSON.stringify。JSON.parse 方法 将一个 JSON 字符串转化为 JavaScript 对象,而 JSON.stringify 方法将 JavaScript 对象转化为 JSON 字符串。由于 JavaScript 对象可能包含循环结构,因此 JSON.stringify(value, replacer, space) 方法包含一个 replacer 参数,用于选择性的转化 JavaScript 对象。例如:

    function replacer(key, value) {
        var omits = ['parent', 'previous', 'next'];
        if (omits.indexOf(key) == -1) return value;
    }
    
    JSON.stringify(posts, replacer, 4);
    

    上面的例子中,JSON.stringify 转换时将忽略 posts 对象及其子对象中的名称为 'parent','previous','next' 的属性。最后一个参数表示用 4 个空格缩进转换的结果。

    参考资料:

    [1] Representational state transfer - Wikipedia
    [2] REST - 维基百科
    [3] 轻的,谁都会写的Service方案--REST与JSON
    [4] 深入浅出REST
    [5] 介绍 JSON
    [6] A RESTful Web service, an example
    [7] http - PUT vs POST in REST - Stack Overflow
    [8] Creating a REST API using Node.js, Express, and MongoDB
    [9] Using native JSON | MDN

    注记:2013 年 6 月 15 日更新。

  • 相关阅读:
    【题解】Luogu P4391 [BOI2009]Radio Transmission 无线传输
    kmp匹配详解
    点分治详解
    【题解】Luogu P3871 [TJOI2010]中位数
    树链剖分详解
    【题解】Luogu P3901 数列找不同
    【题解】Luogu P1503 鬼子进村
    【题解】 P2234 [HNOI2002]营业额统计
    Splay详解
    JSOI2020备考知识点复习
  • 原文地址:https://www.cnblogs.com/zoho/p/2558815.html
Copyright © 2011-2022 走看看