【C++】jsoncpp封装和解析字符串、数字、布尔值和数组

使用jsoncpp进行字符串、数字、布尔值和数组的封装与解析。

1)下载jsoncpp的代码库 百度网盘地址 :jsoncpp.zip_免费高速下载|百度网盘-分享无限制

2)解压缩文件 jsoncpp.rar

unzip jsoncpp.rar

3)修改jsoncpp/src/main.cpp文件

vim src/main.cpp
  1 #include <string>
  2 #include <json/json.h>
  3 #include "stdio.h"
  4 
  5 int ReadJson(const std::string &);
  6 std::string writeJson();
  7 
  8 int main(int argc, char** argv)
  9 {
 10     using namespace std;
 11 
 12     std::string strMsg;
 13 
 14     cout<<"--------------------------------"<<endl;
 15     strMsg = writeJson();
 16     cout<< "json write : " << endl << strMsg << endl;
 17     cout<<"--------------------------------"<<endl;
 18     cout<< "json read :" << endl;
 19     ReadJson(strMsg);
 20     cout<<"--------------------------------"<<endl;
 21 
 22     return 0;
 23 }
 24 
 25 int ReadJson(const std::string & strValue) 
 26 {
 27     using namespace std;
 28 
 29     Json::Reader reader;
 30     Json::Value value;
 31 
 32     if (reader.parse(strValue, value))
 33     {
 34         //解析json中的对象
 35         string out = value["name"].asString();
 36         cout << "name : "   << out << endl;
 37         cout << "number : " << value["number"].asInt() << endl;
 38         cout << "value : "  << value["value"].asBool() << endl;
 39         cout << "no such num : " << value["haha"].asInt() << endl;
 40         cout << "no such str : " << value["hehe"].asString() << endl;
 41 
 42         //解析数组对象
 43         const Json::Value arrayNum = value["arrnum"];
 44         for (unsigned int i = 0; i < arrayNum.size(); i++)
 45         {
 46             cout << "arrnum[" << i << "] = " << arrayNum[i];
 47         }
 48         //解析对象数组对象
 49         Json::Value arrayObj = value["array"];
 50         cout << "array size = " << arrayObj.size() << endl;
 51         for(unsigned int i = 0; i < arrayObj.size(); i++)
 52         {
 53             cout << arrayObj[i];
 54         }
 55         //从对象数组中找到想要的对象
 56         for(unsigned int i = 0; i < arrayObj.size(); i++)
 57         {
 58             if (arrayObj[i].isMember("string")) 
 59             {
 60                 out = arrayObj[i]["string"].asString();
 61                 std::cout << "string : " << out << std::endl;
 62             }
 63         }
 64     }
 65 
 66     return 0;
 67 }
 68 
 69 std::string writeJson() 
 70 {
 71     using namespace std;
 72 
 73     Json::Value root;
 74     Json::Value arrayObj;
 75     Json::Value item;
 76     Json::Value iNum;
 77 
 78     item["string"]    = "this is a string";
 79     item["number"]    = 999;
 80     item["aaaaaa"]    = "bbbbbb";
 81     arrayObj.append(item);
 82 
 83     //直接对jsoncpp对象以数字索引作为下标进行赋值,则自动作为数组
 84     iNum[1] = 1;
 85     iNum[2] = 2;
 86     iNum[3] = 3;
 87     iNum[4] = 4;
 88     iNum[5] = 5;
 89     iNum[6] = 6;
 90 
 91     //增加对象数组
 92     root["array"]    = arrayObj;
 93     //增加字符串
 94     root["name"]    = "json";
 95     //增加数字
 96     root["number"]    = 666;
 97     //增加布尔变量
 98     root["value"]    = true;
 99     //增加数字数组
100     root["arrnum"]    = iNum;
101 
102     root.toStyledString();
103     string out = root.toStyledString();
104 
105     return out;
106 }

4)在目录jsoncpp/ 下执行make命令

jsoncpp$ make
mkdir -p objs/src/json;  mkdir -p objs/src;
g++ -c -Wall -Werror -g -I include src/json/json_reader.cpp -o objs/src/json/json_reader.o
g++ -c -Wall -Werror -g -I include src/json/json_value.cpp -o objs/src/json/json_value.o
g++ -c -Wall -Werror -g -I include src/json/json_writer.cpp -o objs/src/json/json_writer.o
g++ -c -Wall -Werror -g -I include src/main.cpp -o objs/src/main.o
g++  objs/src/json/json_reader.o objs/src/json/json_value.o objs/src/json/json_writer.o objs/src/main.o -o main

5)运行jsoncpp/下的main文件

./main

6)运行结果如下

fengbo: jsoncpp$ ./main 
--------------------------------
json write : 
{
   "array" : [
      {
         "aaaaaa" : "bbbbbb",
         "number" : 999,
         "string" : "this is a string"
      }
   ],
   "arrnum" : [ null, 1, 2, 3, 4, 5, 6 ],
   "name" : "json",
   "number" : 666,
   "value" : true
}

--------------------------------
json read :
name : json
number : 666
value : 1
no such num : 0
no such str : 
arrnum[0] = null
arrnum[1] = 1
arrnum[2] = 2
arrnum[3] = 3
arrnum[4] = 4
arrnum[5] = 5
arrnum[6] = 6
array size = 1

{
    "aaaaaa" : "bbbbbb",
    "number" : 999,
    "string" : "this is a string"
}
string : this is a string
--------------------------------

本文转自郝峰波博客园博客,原文链接:http://www.cnblogs.com/fengbohello/p/4066254.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 JsonCPP 库实现根据字符串查找多个 JSON 节点并按照层级关系进行存储的示例代码: ```c++ #include <iostream> #include <fstream> #include <string> #include <vector> #include "json/json.h" using namespace std; void findNodes(Json::Value& root, const string& nodeName, vector<Json::Value*>& nodes) { if (root.isArray()) { for (int i = 0; i < root.size(); i++) { findNodes(root[i], nodeName, nodes); } } else if (root.isObject()) { if (root.isMember(nodeName)) { nodes.push_back(&root[nodeName]); } for (Json::ValueIterator it = root.begin(); it != root.end(); it++) { findNodes(*it, nodeName, nodes); } } } Json::Value* getNodeByPath(Json::Value& root, vector<string>& path) { if (path.empty()) { return &root; } string nodeName = path[0]; path.erase(path.begin()); if (root.isArray()) { int index = stoi(nodeName); if (index < root.size()) { return getNodeByPath(root[index], path); } } else if (root.isObject()) { if (root.isMember(nodeName)) { return getNodeByPath(root[nodeName], path); } } return nullptr; } void storeNodes(Json::Value& root, vector<Json::Value*>& nodes, vector<string>& path, Json::Value& result) { if (nodes.empty()) { return; } string nodeName = path.empty() ? "" : path.back(); path.pop_back(); Json::Value& node = *nodes.back(); nodes.pop_back(); if (path.empty()) { if (nodeName.empty()) { result.append(node); } else { result[nodeName] = node; } } else { Json::Value& parent = *getNodeByPath(result, path); if (parent.isArray()) { int index = stoi(nodeName); if (index >= parent.size()) { parent.resize(index + 1); } storeNodes(parent[index], nodes, path, result); } else if (parent.isObject()) { storeNodes(parent[nodeName], nodes, path, result); } } } int main() { // 读取 JSON 文件 ifstream file("data.json"); string jsonStr((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); file.close(); // 解析 JSON 字符串 Json::Value root; Json::CharReaderBuilder builder; Json::CharReader* reader = builder.newCharReader(); string errors; bool success = reader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.size(), &root, &errors); delete reader; if (!success) { cout << "Failed to parse JSON: " << errors << endl; return 1; } // 查找节点 string nodeName = "id"; vector<Json::Value*> nodes; findNodes(root, nodeName, nodes); // 存储节点 Json::Value result(Json::arrayValue); for (Json::Value* node : nodes) { vector<string> path; for (Json::Value* parent = node; parent != &root; parent = parent->getParent()) { path.insert(path.begin(), parent->isObject() ? parent->getMemberName(0) : to_string(parent->getIndex())); } storeNodes(root, vector<Json::Value*>({ node }), path, result); } // 输出结果 Json::StreamWriterBuilder writerBuilder; writerBuilder["indentation"] = "\t"; unique_ptr<Json::StreamWriter> writer(writerBuilder.newStreamWriter()); writer->write(result, &cout); return 0; } ``` 在上述代码,我们首先使用 `Json::CharReader` 类将 JSON 文件解析JsonCPP 的 `Value` 对象。然后我们使用 `findNodes()` 函数查找指定节点名称的所有节点,并将其存储到一个 `vector` 。我们使用 `getNodeByPath()` 函数根据节点路径获取节点对象。最后,我们使用 `storeNodes()` 函数将节点按照层级关系进行存储,存储结果保存在一个 `Json::Value` 对象,并使用 `Json::StreamWriter` 类将存储结果输出到控制台。 需要注意的是,上述代码的 `findNodes()` 函数只能查找对象的节点,而不能查找数组的节点。如果需要查找数组的节点,可以将 `findNodes()` 函数修改为递归遍历整个 JSON 树。此外,上述代码还没有进行错误处理,例如当节点路径不存在时,`getNodeByPath()` 函数会返回 `nullptr`,需要在调用该函数时进行判断。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值