在C語言中獲取JSON格式的數據可以使用一些開源的第三方庫,例如json-c和cJSON等。這里以json-c為例來介紹獲取JSON串中數據庫信息的方法。
#include <stdio.h>
#include <stdlib.h>
#include <json-c/json.h>
int main()
{
const char *json_str = "{\"database\":{\"username\":\"root\",\"password\":\"123456\",\"dbname\":\"test\"}}";
struct json_object *json_obj = json_tokener_parse(json_str);
struct json_object *database_obj;
if(json_object_object_get_ex(json_obj, "database", &database_obj)){
struct json_object *username_obj;
struct json_object *password_obj;
struct json_object *dbname_obj;
if(json_object_object_get_ex(database_obj,"username", &username_obj)){
printf("username:%s\n", json_object_get_string(username_obj));
}
if(json_object_object_get_ex(database_obj,"password", &password_obj)){
printf("password:%s\n", json_object_get_string(password_obj));
}
if(json_object_object_get_ex(database_obj,"dbname", &dbname_obj)){
printf("dbname:%s\n", json_object_get_string(dbname_obj));
}
}
json_object_put(json_obj);
return 0;
}
該段代碼解析JSON串中的database對象,并逐個獲取其下的username、password和dbname信息,并打印到控制臺上。