下载
bash
git clone https://github.com/DaveGamble/cJSON.git
保留cJSON.h和cJSON.c即可。
序列化和反序列化
cpp
root@DESKTOP:~/project/cjson_demo$ cat main.cpp
#include <iostream>
#include "cJSON.h"
using namespace std;
class SystemInfo {
public:
std::string m_msg_id;
std::string m_time;
int m_err;
std::string m_err_msg;
std::string m_ntp_address;
//反序列化(解析)
int SetJsonStr(const std::string& json) {
cJSON *js = cJSON_Parse(json.c_str());
if (js == NULL) {
return -1;
}
try {
cJSON *item = cJSON_GetObjectItem(js, "msg_id");
if (item != NULL && cJSON_IsString(item)) {
m_msg_id = item->valuestring;
}
item = cJSON_GetObjectItem(js, "time");
if (item != NULL && cJSON_IsString(item)) {
m_time = item->valuestring;
}
item = cJSON_GetObjectItem(js, "err");
if (item != NULL && cJSON_IsNumber(item)) {
m_err = item->valueint;
}
item = cJSON_GetObjectItem(js, "err_msg");
if (item != NULL && cJSON_IsString(item)) {
m_err_msg = item->valuestring;
}
item = cJSON_GetObjectItem(js, "data");
if (item != NULL && cJSON_IsObject(item)) {
cJSON *it = cJSON_GetObjectItem(item, "ntp_address");
if (it != NULL && cJSON_IsString(it)) {
m_ntp_address = it->valuestring;
}
}
cJSON_Delete(js);
return 0;
} catch (...) {
cJSON_Delete(js);
return -1;
}
}
//序列化(生成)
std::string GetJsonStr() {
cJSON *js = cJSON_CreateObject();
cJSON_AddStringToObject(js, "msg_id", m_msg_id.c_str());
cJSON_AddStringToObject(js, "time", m_time.c_str());
cJSON_AddNumberToObject(js, "err", m_err);
cJSON_AddStringToObject(js, "err_msg", m_err_msg.c_str());
cJSON *item = cJSON_AddObjectToObject(js, "data");
cJSON_AddStringToObject(item, "ntp_address", m_ntp_address.c_str());
char* json_str = cJSON_PrintUnformatted(js);
std::string result(json_str);
free(json_str);
cJSON_Delete(js);
return result;
}
};
int main() {
const char *json_str = "{\"msg_id\":\"1211232322321111222\",\"time\":\"1356443343\",\"err\":0,\"err_msg\":\"成功\",\"data\":{\"ntp_address\":\"8.8.8.8\"}}";
printf("cJSON Version:%s\n", cJSON_Version());
SystemInfo info;
info.SetJsonStr(string(json_str));
string serialized_json = info.GetJsonStr();
cout << "Serialized JSON:\n" << serialized_json << endl;
return 0;
}
编译运行
bash
root@DESKTOP:~/project/cjson_demo$ ls -l
total 100
-rw-r--r-- 1 root root78291 Apr 16 10:59 cJSON.c
-rw-r--r-- 1 root root16193 Apr 16 10:59 cJSON.h
-rw-r--r-- 1 root root 2575 Apr 16 14:42 main.cpp
root@DESKTOP:~/project/cjson_demo$
root@DESKTOP:~/project/cjson_demo$ g++ main.cpp cJSON.c
root@DESKTOP:~/project/cjson_demo$
root@DESKTOP:~/project/cjson_demo$ ./a.out
cJSON Version:1.7.17
Serialized JSON:
{"msg_id":"1211232322321111222","time":"1356443343","err":0,"err_msg":"成功","data":{"ntp_address":"8.8.8.8"}}
root@DESKTOP:~/project/cjson_demo$