JSON-C結構介紹、使用

來源:互聯網
上載者:User

標籤:gcc   json   結構   object   xml   

官方網站介紹http://www.json.org

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結構體如下:

typedefstruct cJSON {

structcJSON *next,*prev;

struct cJSON *child;

int type;

char * valuestring;

int valueint;

double valuedouble;

char *string;

}cJSON;

1、cJSON儲存的時候是採用鏈表格儲存體的,其訪問方式像一顆樹。每一個節點可以有兄妹節點和子節點,通過next/prev指標來尋找上一節點或者下一節點;每個節點通過child指標來訪問,進入下一層。

2、type一共有7種取值,分別是:

#define cJSON_False 0

#define cJSON_True 1

#define cJSON_NULL 2

#define cJSON_Number 3

#define cJSON_String 4

#define cJSON_Array 5

#define cJSON_Object 6

得到其職:

若是Number類型,則valueint或valuedouble中儲存著值,若你期望的是int,則訪問valueint,若期望的是double,則訪問valuedouble,可以得到值。若是String類型的,則valuestring中儲存著值,可以訪問valuestring得到值。

若是多層嵌套的結構體要一層一層的進入,取值。

執行個體:截取部分代碼

JSON結構體

多層嵌套:

{
    "glossary": {
        "title": "example glossary",
"GlossDiv": {
            "title": "S",
"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
                    },
"GlossSee": "markup"
                }
            }
        }
    }
}

cJSON *glossary = cJSON_GetObjectItem(json,"glossary");
char *title = cJSON_GetObjectItem(glossary,"title")->valuestring;
printf("title===%s\n",title);

上傳檔案內有JSON所有可能用到的函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.