c++ json 库调用

选择json库

CJsonObject是基于cJSON全新开发一个C++版的JSON库,CJsonObject的最大优势是轻量(只有4个文件,拷贝到自己代码里即可,无须编译成库,且跨平台和编译器)、简单好用,开发效率极高。

参考GitHub地址:https://github.com/Bwar/CJsonObject

Demo

json目录

新建json目录将CJsonObject里的四个文件放到json目录里。

子目录新建CMakeLists

在json目录里新建CMakeLists.txt

# 查找当前目录下的所有源文件
# 并将名称保存到 DIR_LIB_SRCS 变量
aux_source_directory(. DIR_LIB_SRCS)

# 生成链接库
add_library (cJsonObject ${DIR_LIB_SRCS})

#将当前目录加入到Include的头文件的查找目录
target_include_directories(cJsonObject PUBLIC ./)

demo.cpp

在主目录下新建demo文件

#include <string>
#include <iostream>
#include "CJsonObject.hpp"

int main()
{
    int iValue;
    double fTimeout;
    std::string strValue;
    neb::CJsonObject oJson("{\"refresh_interval\":60,"
                        "\"test_float\":[18.0, 10.0, 5.0],"
                        "\"timeout\":12.5,"
                        "\"dynamic_loading\":["
                            "{"
                                "\"so_path\":\"plugins/User.so\", \"load\":false, \"version\":1,"
                                "\"cmd\":["
                                     "{\"cmd\":2001, \"class\":\"neb::CmdUserLogin\"},"
                                     "{\"cmd\":2003, \"class\":\"neb::CmdUserLogout\"}"
                                "],"
                                "\"module\":["
                                     "{\"path\":\"im/user/login\", \"class\":\"neb::ModuleLogin\"},"
                                     "{\"path\":\"im/user/logout\", \"class\":\"neb::ModuleLogout\"}"
                                "]"
                             "},"
                             "{"
                             "\"so_path\":\"plugins/ChatMsg.so\", \"load\":false, \"version\":1,"
                                 "\"cmd\":["
                                      "{\"cmd\":2001, \"class\":\"neb::CmdChat\"}"
                                 "],"
                             "\"module\":[]"
                             "}"
                        "]"
                    "}");
     std::cout << oJson.ToString() << std::endl;
     std::cout << "-------------------------------------------------------------------" << std::endl;
     std::cout << oJson["dynamic_loading"][0]["cmd"][1]("class") << std::endl;
     oJson["dynamic_loading"][0]["cmd"][0].Get("cmd", iValue);
     std::cout << "iValue = " << iValue << std::endl;
     oJson["dynamic_loading"][0]["cmd"][0].Replace("cmd", -2001);
     oJson["dynamic_loading"][0]["cmd"][0].Get("cmd", iValue);
     std::cout << "iValue = " << iValue << std::endl;
     oJson.Get("timeout", fTimeout);
     std::cout << "fTimeout = " << fTimeout << std::endl;
     oJson["dynamic_loading"][0]["module"][0].Get("path", strValue);
     std::cout << "strValue = " << strValue << std::endl;
     std::cout << "-------------------------------------------------------------------" << std::endl;
     oJson.AddEmptySubObject("depend");
     oJson["depend"].Add("nebula", "https://github.com/Bwar/Nebula");
     oJson["depend"].AddEmptySubArray("bootstrap");
     oJson["depend"]["bootstrap"].Add("BEACON");
     oJson["depend"]["bootstrap"].Add("LOGIC");
     oJson["depend"]["bootstrap"].Add("LOGGER");
     oJson["depend"]["bootstrap"].Add("INTERFACE");
     oJson["depend"]["bootstrap"].Add("ACCESS");
     std::cout << oJson.ToString() << std::endl;
     std::cout << "-------------------------------------------------------------------" << std::endl;
     std::cout << oJson.ToFormattedString() << std::endl;

     std::cout << "-------------------------------------------------------------------" << std::endl;
     neb::CJsonObject oCopyJson = oJson;
     if (oCopyJson == oJson)
     {
         std::cout << "json equal" << std::endl;
     }
     oCopyJson["depend"]["bootstrap"].Delete(1);
     oCopyJson["depend"].Replace("nebula", "https://github.com/Bwar/CJsonObject");
     std::cout << oCopyJson.ToString() << std::endl;
     std::cout << "-------------------------key traverse------------------------------" << std::endl;
     std::string strTraversing;
     while(oJson["dynamic_loading"][0].GetKey(strTraversing))
     {
         std::cout << "traversing:  " << strTraversing << std::endl;
     }
     std::cout << "---------------add a new key, then key traverse---------------------" << std::endl;
     oJson["dynamic_loading"][0].Add("new_key", "new_value");
     while(oJson["dynamic_loading"][0].GetKey(strTraversing))
     {
         std::cout << "traversing:  " << strTraversing << std::endl;
     }

     std::cout << oJson["test_float"].GetArraySize() << std::endl;
     float fTestValue = 0.0;
     for (int i = 0; i < oJson["test_float"].GetArraySize(); ++i)
     {
         oJson["test_float"].Get(i, fTestValue);
         std::cout << fTestValue << std::endl;
     }
     oJson.AddNull("null_value");
     std::cout << oJson.IsNull("test_float") << "\t" << oJson.IsNull("null_value") << std::endl;
     oJson["test_float"].AddNull();
     std::cout << oJson.ToString() << std::endl;

}

主目录新建CMakeLists

在主目录里新建CMakeLists.txt

# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)

# 项目信息
project (jsonDemo)


# 添加子目录
add_subdirectory(json)

# 指定生成目标 
add_executable(jsonDemo demo.cpp)

# 添加链接库
target_link_libraries(jsonDemo cJsonObject)

编译运行

root@default:/share/json# ls
CMakeLists.txt  demo.cpp  json
root@default:/share/json# ls json/
CJsonObject.cpp  CJsonObject.hpp  CMakeLists.txt  cJSON.c  cJSON.h
root@default:/share/json# mkdir build
root@default:/share/json# cd build
root@default:/share/json/build# cmake ..
-- The C compiler identification is GNU 8.4.0
。。。
-- Configuring done
-- Generating done
-- Build files have been written to: /share/json/build
root@default:/share/json/build# make
。。。

运行结果

root@default:/share/json/build# ./jsonDemo 
{"refresh_interval":60,"test_float":[18.000000,10.000000,5.000000],"timeout":12.500000,"dynamic_loading":[{"so_path":"plugins/User.so","load":false,"version":1,"cmd":[{"cmd":2001,"class":"neb::CmdUserLogin"},{"cmd":2003,"class":"neb::CmdUserLogout"}],"module":[{"path":"im/user/login","class":"neb::ModuleLogin"},{"path":"im/user/logout","class":"neb::ModuleLogout"}]},{"so_path":"plugins/ChatMsg.so","load":false,"version":1,"cmd":[{"cmd":2001,"class":"neb::CmdChat"}],"module":[]}]}
-------------------------------------------------------------------
neb::CmdUserLogout
iValue = 2001
iValue = -2001
fTimeout = 12.5
strValue = im/user/login
-------------------------------------------------------------------
{"refresh_interval":60,"test_float":[18.000000,10.000000,5.000000],"timeout":12.500000,"dynamic_loading":[{"so_path":"plugins/User.so","load":false,"version":1,"cmd":[{"cmd":-2001,"class":"neb::CmdUserLogin"},{"cmd":2003,"class":"neb::CmdUserLogout"}],"module":[{"path":"im/user/login","class":"neb::ModuleLogin"},{"path":"im/user/logout","class":"neb::ModuleLogout"}]},{"so_path":"plugins/ChatMsg.so","load":false,"version":1,"cmd":[{"cmd":2001,"class":"neb::CmdChat"}],"module":[]}],"depend":{"nebula":"https://github.com/Bwar/Nebula","bootstrap":["BEACON","LOGIC","LOGGER","INTERFACE","ACCESS"]}}
-------------------------------------------------------------------
{
        "refresh_interval":     60,
        "test_float":   [18.000000, 10.000000, 5.000000],
        "timeout":      12.500000,
        "dynamic_loading":      [{
                        "so_path":      "plugins/User.so",
                        "load": false,
                        "version":      1,
                        "cmd":  [{
                                        "cmd":  -2001,
                                        "class":        "neb::CmdUserLogin"
                                }, {
                                        "cmd":  2003,
                                        "class":        "neb::CmdUserLogout"
                                }],
                        "module":       [{
                                        "path": "im/user/login",
                                        "class":        "neb::ModuleLogin"
                                }, {
                                        "path": "im/user/logout",
                                        "class":        "neb::ModuleLogout"
                                }]
                }, {
                        "so_path":      "plugins/ChatMsg.so",
                        "load": false,
                        "version":      1,
                        "cmd":  [{
                                        "cmd":  2001,
                                        "class":        "neb::CmdChat"
                                }],
                        "module":       []
                }],
        "depend":       {
                "nebula":       "https://github.com/Bwar/Nebula",
                "bootstrap":    ["BEACON", "LOGIC", "LOGGER", "INTERFACE", "ACCESS"]
        }
}
-------------------------------------------------------------------
json equal
{"refresh_interval":60,"test_float":[18.000000,10.000000,5.000000],"timeout":12.500000,"dynamic_loading":[{"so_path":"plugins/User.so","load":false,"version":1,"cmd":[{"cmd":-2001,"class":"neb::CmdUserLogin"},{"cmd":2003,"class":"neb::CmdUserLogout"}],"module":[{"path":"im/user/login","class":"neb::ModuleLogin"},{"path":"im/user/logout","class":"neb::ModuleLogout"}]},{"so_path":"plugins/ChatMsg.so","load":false,"version":1,"cmd":[{"cmd":2001,"class":"neb::CmdChat"}],"module":[]}],"depend":{"nebula":"https://github.com/Bwar/CJsonObject","bootstrap":["BEACON","LOGGER","INTERFACE","ACCESS"]}}
-------------------------key traverse------------------------------
traversing:  so_path
traversing:  load
traversing:  version
traversing:  cmd
traversing:  module
---------------add a new key, then key traverse---------------------
traversing:  so_path
traversing:  load
traversing:  version
traversing:  cmd
traversing:  module
traversing:  new_key
3
18
10
5
0       1
{"refresh_interval":60,"test_float":[18.000000,10.000000,5.000000,null],"timeout":12.500000,"dynamic_loading":[{"so_path":"plugins/User.so","load":false,"version":1,"cmd":[{"cmd":-2001,"class":"neb::CmdUserLogin"},{"cmd":2003,"class":"neb::CmdUserLogout"}],"module":[{"path":"im/user/login","class":"neb::ModuleLogin"},{"path":"im/user/logout","class":"neb::ModuleLogout"}],"new_key":"new_value"},{"so_path":"plugins/ChatMsg.so","load":false,"version":1,"cmd":[{"cmd":2001,"class":"neb::CmdChat"}],"module":[]}],"depend":{"nebula":"https://github.com/Bwar/Nebula","bootstrap":["BEACON","LOGIC","LOGGER","INTERFACE","ACCESS"]},"null_value":null}

Demo1

添加demo1.cpp

在主目录下添加demo1.cpp

#include <string>
#include <iostream>
#include "CJsonObject.hpp"

int main()
{
	int iValue;
	double fTimeout;
	std::string strValue;
	neb::CJsonObject oJson("{}");

	oJson.AddEmptySubObject("person");
	oJson["person"].Add("info", "person json");
	oJson["person"].AddEmptySubArray("student");
	oJson["person"]["student"].Add("BEACON");
	oJson["person"]["student"].Add("LOGIC");
	oJson["person"]["student"].Add("LOGGER");

	std::cout << oJson.ToString() << std::endl;
	std::cout << "-------------------------------------------------------------------" << std::endl;
	std::cout << oJson.ToFormattedString() << std::endl;

	std::cout << "-------------------------------------------------------------------" << std::endl;
	neb::CJsonObject oCopyJson = oJson;
	if (oCopyJson == oJson)
	{
	 std::cout << "json equal" << std::endl;
	}
	oCopyJson["person"]["student"].Delete(2);
	oCopyJson["person"].Replace("info", "wo shi xzw");
	std::cout << oCopyJson.ToString() << std::endl;
	std::cout << "-------------------------key traverse------------------------------" << std::endl;
	std::string strTraversing;
	while(oJson["person"][1].GetKey(strTraversing))
	{
	 std::cout << "traversing:  " << strTraversing << std::endl;
	}
	std::cout << "---------------add a new key, then key traverse---------------------" << std::endl;
	oJson["person"].AddEmptySubArray("age");
	oJson["person"]["age"].Add(28);
	std::cout << oJson.ToString() << std::endl;
}

修改CMakeLists

# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)

# 项目信息
project (jsonDemo)

# 添加子目录
add_subdirectory(json)

# 指定生成目标 
add_executable(jsonDemo demo.cpp)

# 添加链接库
target_link_libraries(jsonDemo cJsonObject)

# 指定生成目标 
add_executable(jsonDemo1 demo1.cpp)

# 添加链接库
target_link_libraries(jsonDemo1 cJsonObject)

编译运行

编译:

root@default:/share/json# ls
CMakeLists.txt  build  demo.cpp  demo1.cpp  json

root@default:/share/json# cd build/
root@default:/share/json/build# cmake ..
-- The C compiler identification is GNU 8.4.0
。。。
-- Build files have been written to: /share/json/build

root@default:/share/json/build# make
Scanning dependencies of target cJsonObject
[ 14%] Building CXX object json/CMakeFiles/cJsonObject.dir/CJsonObject.cpp.o
。。。
[100%] Built target jsonDemo1

root@default:/share/json/build# ls
CMakeCache.txt  CMakeFiles  Makefile  cmake_install.cmake  json  jsonDemo  jsonDemo1

运行:

root@default:/share/json/build# ./jsonDemo1
{"person":{"info":"person json","student":["BEACON","LOGIC","LOGGER"]}}
-------------------------------------------------------------------
{
        "person":       {
                "info": "person json",
                "student":      ["BEACON", "LOGIC", "LOGGER"]
        }
}
-------------------------------------------------------------------
json equal
{"person":{"info":"wo shi xzw","student":["BEACON","LOGIC"]}}
-------------------------key traverse------------------------------
---------------add a new key, then key traverse---------------------
{"person":{"info":"person json","student":["BEACON","LOGIC","LOGGER"],"age":[28]}}

添加二维数组

再demo1.cpp中添加

	std::cout << "---------------二维数组---------------------" << std::endl;
	oJson.AddEmptySubArray("xzw_array");
	for(int i=0;i<2;++i){
		neb::CJsonObject demo1;
		neb::CJsonObject demo2;
		demo2.Add("test",i);
		demo1.Add(demo2);
		oJson["xzw_array"].Add(demo1);
	}
	std::cout << oJson.ToString() << std::endl;

运行

---------------二维数组---------------------
{"person":{"info":"person json","student":["BEACON","LOGIC","LOGGER"],"age":[28]},"xzw_array":[[{"test":0}],[{"test":1}]]}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×