c 儲存json資料到結構體
阿新 • • 發佈:2019-01-27
在c語言跟android打交道時,避免不了從android層傳遞json資料到c層,如果傳來的是一個配置項,儲存到c的結構體中,如果配置項中有一、兩項,那一個一個解析放到結構體中也並不麻煩,問題來了,如果配置項多一些就顯的程式碼冗餘並且比較麻煩,這裡總結了個小方法:
#include "cjson.h"
typedef unsigned char uint8_t
struct __cache_info {
char *site;
char *vd;
char *params;
char *url;
char *desturl_prefix;
char *headers;
} cache_info;
static bool set_cache_info(cache_info *info, const char *json_opts)
{
if (!info || !json_opts)
return false;
enum Types{ mNumber, mString };
struct mc_nodename
{
const char *name;
int type;
int offset;
};
#define OFF(x) offsetof(cache_info, x)
static const mc_nodename nodename[] = {
{ "site", mString, OFF(site) },
{ "vd", mString, OFF(vd) },
{ "params", mString, OFF(params) },
{ "url", mString, OFF(url) },
{ "desturl_prefix", mString, OFF(desturl_prefix) },
{ "headers", mString, OFF(headers) },
{ NULL, 0 , 0 },
};
cJSON *root = cJSON_Parse(json_opts);
if (!root)
return false;
for (int i = 0; nodename[i].name; i++)
{
switch (nodename[i].type)
{
case mString:
{
cJSON* tmp = cJSON_GetObjectItem(root, nodename[i].name);
if (tmp && tmp->type == cJSON_String && tmp->valuestring)
{
LOGD("----- [%s]= %s\n", nodename[i].name, tmp->valuestring);
*(char**)(((uint8_t*)info) + nodename[i].offset) = strdup(tmp->valuestring);
}
break;
}
case mNumber:
{
cJSON* tmp = cJSON_GetObjectItem(root, nodename[i].name);
if (tmp && tmp->type == cJSON_Number && tmp->valuestring)
{
LOGD("----- [%s]= %d\n", nodename[i].name, tmp->valueint);
*(int*)(((uint8_t*)info) + nodename[i].offset) = tmp->valueint;
}
break;
}
}
}
cJSON_Delete(root);
return true;
}