JSON-C结构介绍、使用

官方网站介绍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 LanguageStandard 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 指针来访问,进入下一层。

2type一共有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类型,则valueintvaluedouble中存储着值,若你期望的是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所有可能用到的函数

你可能感兴趣的:(JSON-C结构介绍、使用)