• Jansson库的使用简介


    一、Jansson的安装:

    这里可以直接参考Jansson官方手册第一步:https://jansson.readthedocs.io/en/2.13/gettingstarted.html

    这里暂时介绍在Window条件下,使用CMake+Mingw32配置Jansson库。

    1.直接使用指令的方式,在CMD中按照以下指令操作(使用这种方式跳过步骤2):

    <Uncompress the tar.gz File>
    cd jansson-2.13.1
    md build
    cd build
    cmake -G "MinGW Makefiles" ..
    mingw32-make
    mingw32-make install

    上述等待完成CMake之后生成对应的Makefile,然后再调用make命令,完成对应程序的编译。

    2.使用CMake GUI来进行编译(一般大家在Windows上都是安装的CMake的GUI)

    注1:注意取消勾选JANSSON_BUILD_DOCS.

    注2:注意勾选JANSSON_BUILD_SHRAED_LIBS.这里的勾选非常重要,否则将不会生成对应Windows的dll动态库文件,无法调用Jansson相关的API。

    最后调用mingw32-make完成Jansson库的编译过程.

    完成编译之后使用make install完成对编译的库进行安装,如下:

    mingw32-make.exe install

    3.配置Jansson库的环境变量

    打开PATH路径在其中添加如下环境变量:

     这个是环境变量的前缀设置,避免PATH过长的情况。

    这里是在PATH添加的环境变量,这里添加的是mingw32-make install之后的安装位置的库路径。

     在VSC中配置相关Jansson库,如下所示:

    1 c_cpp_properties.json添加:
    2         "C:/Program Files (x86)/jansson/include",
    3 tasks.json添加:
    4         "-IC:/Program Files (x86)/jansson/include",
    5         "-LC:/Program Files (x86)/jansson/bin/*",
    6         "-LC:/Program Files (x86)/jansson/lib",
    7         "-llibjansson",

     具体参照这里,里面包括了Opencv,不使用Opencv的话,删除Opencv相关内容即可:

    c_cpp_properties.json文件内容:

    {
        "configurations": [
            {
                "name": "Win32",
                "includePath": [
                    "${workspaceFolder}/**",
                    "D:/TDM-GCC-64/include/*",
                    "D:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/include/c++/*",
                    "D:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/include/c++/x86_64-w64-mingw32/*",
                    "D:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/include/c++/backward/*",
                    "D:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/include/*",
                    "D:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/include-fixed",
                    "D:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/include",
                    "C:/Program Files (x86)/jansson/include",
                    "D:/Opencv/opencv/mingw64_build/install/include",
                    "D:/Opencv/opencv/mingw64_build/install/include/opencv2"
                ],
                "defines": [],
                "compilerPath":"D:/TDM-GCC-64/bin/gcc.exe",
                "cStandard": "c11",
                "cppStandard": "c++17",
                "intelliSenseMode": "clang-x64",
                "browse": {
                    "path": [
                        "${workspaceFolder}",
                        "D:/TDM-GCC-64/include/**",
                        "D:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/include",
                        "D:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/include/c++",                  
                        "D:/Opencv/opencv/mingw64_build/install/include",
                        "C:/Program Files (x86)/jansson/include"
                    ],
                    "limitSymbolsToIncludedHeaders": true,
                    "databaseFilename": ""
                }
            }
        ],
        "version": 4
    }
    View Code

    tasks.json文件内容:

    {
        "version": "2.0.0",
        "command": "g++",
        "args": [
            "-g",
            "${file}",
            "-o",
            "${fileBasenameNoExtension}.exe",
            "-ID:/Opencv/opencv/mingw64_build/install/include",
            "-ID:/Opencv/opencv/mingw64_build/install/include/opencv2",
            "-LD:/Opencv/opencv/mingw64_build/install/x64/mingw/lib",
            "-LD:/Opencv/opencv/mingw64_build/install/x64/mingw/bin/*",
            "-IC:/Program Files (x86)/jansson/include",
            "-LC:/Program Files (x86)/jansson/bin/*",
            "-LC:/Program Files (x86)/jansson/lib",
            "-llibjansson",
            "-llibopencv_calib3d420",
            "-llibopencv_core420",
            "-llibopencv_dnn420",
            "-llibopencv_features2d420",
            "-llibopencv_flann420",
            "-llibopencv_highgui420",
            "-llibopencv_imgcodecs420",
            "-llibopencv_imgproc420",
            "-llibopencv_ml420",
            "-llibopencv_objdetect420",
            "-llibopencv_photo420",
            "-llibopencv_stitching420",
            "-llibopencv_video420",
            "-llibopencv_videoio420",
        ],
        "problemMatcher": {
            "owner": "cpp",
            "fileLocation": [
                "relative",
                "${workspaceFolder}"
            ],
            "pattern": {
                "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
                "file": 1,
                "line": 2,
                "column": 3,
                "severity": 4,
                "message": 5
            }
        },
        "group": {
            "kind": "build",
            "isDefault": true
        }
    }
    View Code

    4.测试Jansson安装情况(注意第六行,导入jansson为绝对路径导入)

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <stdfix.h>
     4 #include <string.h>
     5 #include <iostream>
     6 #include <jansson.h>
     7 
     8 using namespace std;
     9 
    10 int main(void)
    11 {
    12     json_t val;
    13     int type = json_typeof(&val);
    14     bool Judge = json_is_object(&val);
    15     std::cout << "json_is_object:" << Judge << std::endl;
    16     printf("Hello Jansson!
    ");
    17     while(1);
    18     return 0;
    19 }

    运行结果如下:

    二、jansson相关的API:

    https://jansson.readthedocs.io/en/latest/apiref.html#c.json_t

    string object array error number

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <stdfix.h>
     4 #include <string.h>
     5 #include <iostream>
     6 #include <jansson.h>
     7 #include <jansson_config.h>
     8 
     9 using namespace std;
    10 
    11 int main() {
    12     json_t val;
    13     json_type eval = JSON_REAL;
    14     bool Judge = 1;
    15     int type = json_typeof(&val); // Get the type of Obj
    16     Judge = json_is_object(&val); // Obj Judge
    17     cout << "json_is_object:" << Judge << endl;
    18     Judge = json_is_array(&val); //Object judged to be array
    19     cout << "Json_is_array:" << Judge << endl;
    20     cout << "The type of val:" << type << endl;
    21 
    22     /* JSON array Defination and value setting */
    23     json_t *array, *integer;
    24     array = json_array(); // Create the json array
    25     integer = json_integer(42); // Create the json integer
    26     json_array_append(array,integer); // Set the value of json array
    27     json_decref(integer); // Drop the content of integer and can no longer be used.
    28 
    29     /* JSON-STRING */
    30     json_auto_t *value = NULL;
    31     value = json_string("Hello"); // Initial a new string json obj
    32     json_string_set(value, "World!"); // Use set func to change the content of json string obj.
    33     size_t len = json_string_length(value); // Get the length of the json string obj.
    34     cout << "The len of value:" << len << endl;
    35 
    36     /* JSON-NUMBER */
    37     json_int_t number; // Define a json type number.
    38     number = 100; // initial the number.
    39     printf("number is %" JSON_INTEGER_FORMAT "
    ",number);
    40     number = json_integer_value(integer); // Get the json type integer's value to number.
    41     printf("value of integer(json_t) is %" JSON_INTEGER_FORMAT "
    ",number); // The integer had been decrefed in line27.(So it's zero)
    42     integer = json_real(3.1415926); // Set a real number value to integer.
    43     double res = json_real_value(integer); // Read out the value to a double type var.(The integer can store the double type json data.)
    44     printf("The res is:%f
    ",res);
    45 
    46     /* JSON-ARRAY */
    47     json_t *Matrix = json_array(); // json array defination.
    48     json_array_append(Matrix,integer); // Add a integer obj to the array.
    49     size_t Matrix_Size = json_array_size(Matrix); // Test the size of the array after add a new integer obj to it.
    50     printf("The size of Matrix:%d
    ",Matrix_Size);
    51 
    52     /* JSON-OBJECT */
    53     json_t *obj = json_object(); // Define a new json obj.
    54     size_t obj_size = json_object_size(obj); // Get the size of the json obj.
    55     printf("The size of obj:%d
    ",obj_size);
    56     char *key = "Hello";
    57     integer = json_integer(52); // Set the value of integer json obj.
    58     int back = json_object_set(obj,key,integer); // Setup a new obj named "Hello" and the mapped value is 52.
    59     json_t *read_num_back = json_object_get(obj,key); // Get back the obj named "Hello".
    60     int num_val = json_integer_value(read_num_back);  // Get the value of the Hello obj.
    61     cout << "The value of integer:" << num_val << endl; // Echo out the Value.
    62 
    63     while(1);
    64     return 0;
    65 }

    程序运行结果:

    三、jansson处理JSON文件:

     首先取JSON文件test.json如下:

     1 {
     2     "deviceList": [{
     3         "id": "fee5e04c50754088913601d733aadea5",
     4         "name": "Company",
     5         "anotherName": "",
     6         "groupName": "Reseach",
     7         "serial": "03307186819I",
     8         "batch": 0,
     9         "model": "A-610",
    10         "ipAddr": "123.54.90.133",
    11         "macAddr": "",
    12         "status": 0,
    13         "isLock": false,
    14         "comment": "",
    15         "createTime": "Jul 15, 2019 1:43:51 PM",
    16         "icreateTime": "",
    17         "heartPort": 12671,
    18         "voltagePort": 12672,
    19         "statusPort": 12673,
    20         "historyPort": 12674,
    21         "statisticPort": 12675,
    22         "logPort": 12676,
    23         "paramPort": 12677,
    24         "lockPort": 12678,
    25         "updatePort": 12679,
    26         "sn": 224,
    27         "projectName": "Lib"
    28     }, {
    29         "id": "cb14cfe4c2874c7387119048dc4f9fe0",
    30         "name": "Company",
    31         "anotherName": "",
    32         "groupName": "xxx",
    33         "serial": "0450019sd89K",
    34         "batch": 0,
    35         "model": "SM-100",
    36         "ipAddr": "229.168.20.221",
    37         "macAddr": "",
    38         "status": 0,
    39         "isLock": false,
    40         "comment": "",
    41         "createTime": "Nov 14, 2019 4:07:55 PM",
    42         "icreateTime": "",
    43         "heartPort": 18341,
    44         "voltagePort": 18342,
    45         "statusPort": 18343,
    46         "historyPort": 18344,
    47         "statisticPort": 18345,
    48         "logPort": 18346,
    49         "paramPort": 18347,
    50         "lockPort": 18348,
    51         "updatePort": 18349,
    52         "sn": 790,
    53         "projectName": ""
    54     }, {
    55         "id": "c149edf863074005876da6a5a22bc9b8",
    56         "name": "Company",
    57         "anotherName": "",
    58         "groupName": "xxx",
    59         "serial": "04510190118K",
    60         "batch": 0,
    61         "model": "SM-100",
    62         "ipAddr": "201.168.23.48",
    63         "macAddr": "",
    64         "status": 0,
    65         "isLock": false,
    66         "comment": "",
    67         "createTime": "Nov 29, 2019 4:13:49 PM",
    68         "icreateTime": "",
    69         "heartPort": 19631,
    70         "voltagePort": 19632,
    71         "statusPort": 19633,
    72         "historyPort": 19634,
    73         "statisticPort": 19635,
    74         "logPort": 19636,
    75         "paramPort": 19637,
    76         "lockPort": 19638,
    77         "updatePort": 19639,
    78         "sn": 979,
    79         "projectName": ""
    80     }],
    81     "url":"www.baidu.com",
    82     "frequency":50
    83 }
    View Code

    其中包括了数组array格式数据,整数、字符串等。

    以下代码对此Json文件进行了各方面的解析,具体如下:

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <stdfix.h>
     4 #include <string.h>
     5 #include <iostream>
     6 #include <jansson.h>
     7 #include <jansson_config.h>
     8 
     9 using namespace std;
    10 
    11 int main(void)
    12 {
    13     printf("Hello Jansson!
    ");
    14     json_t val;
    15     int type = json_typeof(&val);
    16     bool Judge = json_is_object(&val);
    17     std::cout << "json_is_object:" << Judge << std::endl;
    18 
    19     json_error_t error; // Jansson Error Datatype.
    20     json_t *json_file; // Josn File Point.
    21     
    22     /* Read a JSON mesg from file.json */
    23     json_file = json_load_file("C:/Users/Administrator/Desktop/mamiao/Alg_Cpp/test.json", 0, &error); // Load json form json.json
    24     if(!json_file) printf("No json_file can read!
    "); // Judge the file is right readed.
    25 
    26     size_t obj_size = json_object_size(json_file); // Judge the number of the objects(deviceListurlHEHE).
    27     printf("The size of json_file:%d
    ",obj_size);
    28 
    29     const char *Key_0 = "url"; // Set the key value
    30     json_t *url = json_object_get(json_file,Key_0); // Get the key mapped Json_object data.
    31 
    32     Judge = json_is_string(url); // Judge the obj is string or not?
    33     std::cout << "json_is_string:" << Judge << std::endl;
    34 
    35     size_t str_length = json_string_length(url); // Get the length of the string obj.
    36     std::cout << "The length of url is:" << str_length << std::endl;
    37 
    38     const char *str_res_0 = " "; // Alloc the memory buffer for storage the data of json_object url.
    39     str_res_0 = json_string_value(url); // Get the value of json_object url.
    40     cout << "The length of url is:" << strlen(str_res_0) << endl;
    41     for(int i=0;i<strlen(str_res_0);i++){ // Echo out the url string
    42         cout << *(str_res_0+i);
    43     }
    44     cout << endl;
    45 
    46     /* Get JSON's array value */
    47     const char *Key_1 = "deviceList";
    48     json_t *device = json_object_get(json_file,Key_1); // Get the deviceList array first
    49     Judge = json_is_array(device); // Judge the data to be array
    50     std::cout << "json_is_array:" << Judge << std::endl;
    51 
    52     size_t array_size = json_array_size(device); // Get the size of array
    53     cout << "The size of device array is:" << array_size << endl; // Echo out the size of deviceList array
    54 
    55     json_t *device_0 =  json_array_get(device,1); // Get the Element of deviceList array where the index=1
    56 
    57     const char *Param1 = "id"; // Set the data type you need to get in deviceList_array[1]
    58     json_t *id = json_object_get(device_0,Param1); // Get the id(type) data
    59     Judge = json_is_string(id);  // Judge the data is the right type(string
    umberoolean...)
    60     std::cout << "json_is_string:" << Judge << std::endl;
    61 
    62     const char *id_string = " "; // Alloc the memory buffer for storage the data of json_object id.
    63     id_string = json_string_value(id); // Convert the value to Cpp's string type.
    64     cout << "The length of id is:" << strlen(id_string) << endl; // Checkout the length of the string.
    65     for(int i=0;i<strlen(id_string);i++){  // Show the string on the Terminal.
    66         cout << *(id_string+i);
    67     }
    68     cout << endl;
    69 
    70     /* Get the number value in this JSON */
    71     const char *Key_2 = "frequency"; // // Set the data type you need to get in json_file obj.
    72     json_t *Freq = json_object_get(json_file,Key_2); // Get the frequency obj.
    73     Judge = json_is_integer(Freq); // Judge the data is integer or not?
    74     cout << "The frequency obj is integer:" << Judge << endl;
    75     int Freq_val = json_number_value(Freq); // Get the value of frequency obj.
    76     cout << "The value of Freq:" << Freq_val << endl; // Echo out the value.
    77 
    78     /* Boolean object in JSON read */
    79     const char *Param2 = "isLock"; // Set the data type you need to get in deviceList_array[1]
    80     json_t *Lock_state = json_object_get(device_0,Param2); // Get the isLock(type) status
    81     Judge = json_is_boolean(Lock_state);  // Judge the data is the right type(string
    umberoolean...)
    82     std::cout << "json_is_boolean:" << Judge << std::endl;
    83     bool state = json_boolean_value(Lock_state); // Get the status of the isLock bool data.
    84     if(state){ // Echo out the result.
    85         cout << "It's True." << endl;
    86     }else{
    87         cout << "It's False." << endl;
    88     }
    89 
    90     while(1);
    91     return 0;
    92 }

    在我的设备上运行的结果如下:

    四、从网上获取JSON文件并解析:

    未完待续~

    Reference:

    github官网代码下载:https://github.com/akheron/jansson

    Jansson官方主页面:https://digip.org/jansson/

    Jansson编程手册:https://jansson.readthedocs.io/en/2.13/tutorial.html

    其他参考:https://www.cnblogs.com/lifan3a/articles/10950741.html

  • 相关阅读:
    ffmpeg mp4 视频输出为 aac 的命令
    git操作远程分支
    Linux (openSUSE 15.3 ) server ssh 可以使用,sftp无法使用
    小小思考题
    Linux 命令介绍
    2021 年 如何使用VMware 安装 ubuntu 7.04 虚拟机, 配置 apt 源
    Linux 下 命令行 使用浏览器
    oracle.cmd
    Sqlcmd
    vue eslint 配置使用
  • 原文地址:https://www.cnblogs.com/uestc-mm/p/10793703.html
Copyright © 2020-2023  润新知