JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式,常用于Web應(yīng)用程序中傳遞數(shù)據(jù)。在C語言中,有時(shí)需要手動(dòng)解析JSON包,下面我們來看一下如何進(jìn)行手動(dòng)解析。
//假設(shè)我們有以下JSON數(shù)據(jù) { "name": "小明", "age": 18, "isMale": true, "hobby": ["playing basketball", "listening to music"], "address": { "province": "廣東省", "city": "深圳市", "district": "南山區(qū)" } } //我們定義一個(gè)JSON數(shù)據(jù)結(jié)構(gòu) typedef struct { char name[20]; int age; bool isMale; char hobby[2][20]; char province[10]; char city[10]; char district[10]; } Person; //手動(dòng)解析JSON包 Person person; json_object *obj, *address_obj; json_object *hobby_arr, *hobby_obj1, *hobby_obj2; obj = json_tokener_parse(json_str); json_object_object_get_ex(obj, "name", &tmp); strcpy(person.name, json_object_get_string(tmp)); json_object_object_get_ex(obj, "age", &tmp); person.age = json_object_get_int(tmp); json_object_object_get_ex(obj, "isMale", &tmp); person.isMale = json_object_get_boolean(tmp); json_object_object_get_ex(obj, "hobby", &hobby_arr); hobby_obj1 = json_object_array_get_idx(hobby_arr, 0); hobby_obj2 = json_object_array_get_idx(hobby_arr, 1); strcpy(person.hobby[0], json_object_get_string(hobby_obj1)); strcpy(person.hobby[1], json_object_get_string(hobby_obj2)); json_object_object_get_ex(obj, "address", &address_obj); json_object_object_get_ex(address_obj, "province", &tmp); strcpy(person.province, json_object_get_string(tmp)); json_object_object_get_ex(address_obj, "city", &tmp); strcpy(person.city, json_object_get_string(tmp)); json_object_object_get_ex(address_obj, "district", &tmp); strcpy(person.district, json_object_get_string(tmp));
上面的代碼中,我們首先定義了一個(gè)結(jié)構(gòu)體Person,用于存儲(chǔ)JSON數(shù)據(jù)中的各個(gè)字段。然后用json_tokener_parse函數(shù)將JSON字符串轉(zhuǎn)化為json_object對(duì)象,用json_object_object_get_ex函數(shù)依次獲取JSON數(shù)據(jù)中的各個(gè)字段值,并存儲(chǔ)到Person結(jié)構(gòu)體中。
手動(dòng)解析JSON包需要我們熟悉json-c庫中的函數(shù)和數(shù)據(jù)結(jié)構(gòu),對(duì)于復(fù)雜的JSON數(shù)據(jù)結(jié)構(gòu),手動(dòng)解析可能會(huì)變得非常麻煩,此時(shí)我們可以考慮使用其他第三方庫或者內(nèi)置函數(shù)進(jìn)行解析。