cJson->COM配置文件

file:COM配置文件

{
"com_para":
{
"device":"COM4",
"baud_rate":115200,
"parity":"0",
"bytesize":8,
"stopbits":1
}
}

#include 
#include 
#include 

#include "cJSON.h"

#define Pkgs_File "data\\config.json"

char* GetJsonObject(char* fileName)
{
    long len = 0;
    char* out = NULL;
    int tmp = 0;
    FILE* fp = fopen(fileName, "rb+");
    if (!fp)
    {
        return NULL;
    }
    fseek(fp, 0, SEEK_END);
    len = ftell(fp);
    if (0 == len)
    {
        return NULL;
    }
    fseek(fp, 0, SEEK_SET);
    out = (char*)malloc(sizeof(char)*len);
    tmp = fread(out, 1, len, fp);

    fclose(fp);
    return out;
}
void main()
{
    cJSON* json = NULL;
    char* out = NULL;

    out = GetJsonObject("test.json");
    
    cJSON *root = cJSON_Parse(out);
    if (root == NULL)
    {
        return;
    }

    cJSON *js_list = cJSON_GetObjectItem(root, "com_para");
    if (root == NULL)
    {
        return;
    }
    cJSON *device = cJSON_GetObjectItem(js_list, "device");
    if (device == NULL)
    {
        return;
    }
    cJSON *baud_rate = cJSON_GetObjectItem(js_list, "baud_rate");
    if (baud_rate == NULL)
    {
        return;
    }
    cJSON *parity = cJSON_GetObjectItem(js_list, "parity");
    if (parity == NULL)
    {
        return;
    }
    cJSON *bytesize = cJSON_GetObjectItem(js_list, "bytesize");
    if (bytesize == NULL)
    {
        return;
    }
    cJSON *stopbits = cJSON_GetObjectItem(js_list, "stopbits");
    if (stopbits == NULL)
    {
        return;
    }


    printf("%s, %d, %s, %s, %d, %d\n", device->valuestring,
       &baud_rate->valueint, parity->valuestring, &bytesize->valueint, &stopbits->valueint);

    cJSON_Delete(json);
    free(out);

    getchar();
}

你可能感兴趣的:(cJson->COM配置文件)