• c++ 使用rapidjson对数据序列化和反序列化(vs2109)


      RapidJSON是腾讯开源的一个高效的C++ JSON解析器及生成器,它是只有头文件的C++库,综合性能是最好的。

    1. 安装

    在NuGet中为项目安装tencent.rapidjson

    2. 引用头文件

    #include
    #include
    #include


    3. 头文件定义

    添加测试json字符串和类型对应数组

    1. // 测试json字符串
    2. const char* strJson = "{\"name\":\"MenAngel\",\"age\":23,\"hobbys\":[\"语文\",\"数学\",\"英语\",54],\"scores\":{\"数学\":\"90.6\",\"英语\":\"100.0\", \"语文\":\"80.0\"}}";
    3. // 数据类型,和 rapidjson的enum Type 相对应
    4. static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };

     

    4.  修改JSON 内容

    1. /// <summary>
    2. /// 修改JSON 内容
    3. /// </summary>
    4. void MyRapidJson::alterJson()
    5. {
    6. rapidjson::Document doc;
    7. doc.Parse(strJson);
    8. cout << "修改前: " << strJson <<"\n" << endl;
    9. // 修改内容
    10. rapidjson::Value::MemberIterator iter = doc.FindMember("name");
    11. if (iter != doc.MemberEnd())
    12. doc["name"] = "张三";
    13. iter = doc.FindMember("age");
    14. if (iter != doc.MemberEnd())
    15. {
    16. rapidjson::Value& v1 = iter->value;
    17. v1 = "40";
    18. }
    19. // 修改后的内容写入 StringBuffer 中
    20. rapidjson::StringBuffer buffer;
    21. rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    22. doc.Accept(writer);
    23. cout <<"修改后: " << buffer.GetString() << "\n" << endl;
    24. }

    运行结果:

    {"name":"张三","age":"40","hobbys":["语文","数学","英语",54],"scores":{"数学":"90.6","英语":"100.0","语文":"80.0"}}

    5. 生成 json 数据

    1. /// <summary>
    2. /// 生成JSON数据
    3. /// </summary>
    4. void MyRapidJson::createJson()
    5. {
    6. // 1.准备数据
    7. string name = "王五";
    8. string gender = "boy";
    9. int age = 23;
    10. bool student = true;
    11. vector<string> hobbys = { "语文","数学","英语" };
    12. map<string, double> scores = { {"语文",80},{"数学",90},{"英语",100} };
    13. //2.初始化DOM
    14. rapidjson::Document doc;
    15. rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();
    16. doc.SetObject();
    17. // 添加数据
    18. /* 字符串添加 */
    19. rapidjson::Value tempValue1;
    20. tempValue1.SetString(name.c_str(), allocator);
    21. doc.AddMember("name", tempValue1, allocator);
    22. rapidjson::Value tempValue2(rapidjson::kStringType);
    23. tempValue2.SetString(gender.c_str(), allocator);
    24. doc.AddMember(rapidjson::StringRef("gender"), tempValue2, allocator);
    25. /* 数字类型添加 */
    26. doc.AddMember("age", age, allocator);
    27. /* bool 类型 */
    28. rapidjson::Value tempValueStu(rapidjson::kTrueType);
    29. tempValueStu.SetBool(student);
    30. doc.AddMember(rapidjson::StringRef("student"), tempValueStu, allocator);
    31. /* Array 添加数据 */
    32. rapidjson::Value tempValue3(rapidjson::kArrayType);
    33. for (auto hobby : hobbys)
    34. {
    35. rapidjson::Value hobbyValue(rapidjson::kStringType);
    36. hobbyValue.SetString(hobby.c_str(), allocator);
    37. tempValue3.PushBack(hobbyValue, allocator);
    38. }
    39. doc.AddMember("hobbys", tempValue3, allocator);
    40. /* Object 添加 */
    41. rapidjson::Value tempValue4(rapidjson::kObjectType);
    42. tempValue4.SetObject();
    43. for (auto score : scores)
    44. {
    45. //rapidjson::Value scoreName(rapidjson::kStringType);
    46. //scoreName.SetString(score.first.c_str(), allocator);
    47. //tempValue4.AddMember(scoreName, score.second, allocator);
    48. // 方法二
    49. rapidjson::Value scoreName(rapidjson::kStringType);
    50. scoreName.SetString(score.first.c_str(), allocator);
    51. rapidjson::Value scoreValue(rapidjson::kStringType);
    52. char charValue[20];
    53. itoa(score.second, charValue,10);
    54. scoreValue.SetString(charValue, allocator);
    55. tempValue4.AddMember(scoreName, scoreValue, allocator);
    56. }
    57. doc.AddMember("scores", tempValue4, allocator);
    58. // 写入 StringBuffer
    59. rapidjson::StringBuffer strBuffer;
    60. rapidjson::Writer<rapidjson::StringBuffer> writer(strBuffer);
    61. doc.Accept(writer);
    62. cout << strBuffer.GetString() << "\n" << endl;
    63. string outFileName = "C:\\Users\\Administrator\\Desktop\\creatJson.txt";
    64. ofstream outfile(outFileName, std::ios::trunc);
    65. outfile << strBuffer.GetString() << endl;
    66. outfile.flush();
    67. outfile.close();
    68. }

    运行结果:

    {"name":"王五","gender":"boy","age":23,"student":true,"hobbys":["语文","数学","英语"],"scores":{"数学":"90","英语":"100","语文":"80"}}

    6. json 数据解析

    1. /// <summary>
    2. /// 查询json 内容
    3. /// </summary>
    4. void MyRapidJson::searchJson()
    5. {
    6. rapidjson::Document doc;
    7. if (doc.Parse(strJson).HasParseError())
    8. {
    9. std::cout << "json 解析错误" << std::endl;
    10. return;
    11. }
    12. cout << "doc 的属性成员有 " << doc.MemberCount() << "个!" << endl;
    13. vector<string> propertyName;
    14. int i = 0;
    15. for (rapidjson::Value::MemberIterator iter = doc.MemberBegin(); iter != doc.MemberEnd(); ++iter)
    16. {
    17. cout << ++i << "、 " << iter->name.GetString() << " is " << kTypeNames[iter->value.GetType()] << endl;
    18. propertyName.push_back(iter->name.GetString());
    19. }
    20. cout << endl;
    21. for (rapidjson::Value::MemberIterator iter = doc.MemberBegin(); iter != doc.MemberEnd(); ++iter)
    22. {
    23. if (iter->value.GetType() == rapidjson::kObjectType || iter->value.GetType() == rapidjson::kArrayType)
    24. cout << iter->name.GetString() << " : " << endl;
    25. else
    26. cout << iter->name.GetString() << " : ";
    27. DfsDocument(std::move(iter->value));
    28. }
    29. }
    30. /// <summary>
    31. /// 遍历里面的内容
    32. /// </summary>
    33. /// <param name="val"></param>
    34. void MyRapidJson::DfsDocument(rapidjson::Value val)
    35. {
    36. if (!val.GetType())
    37. return;
    38. switch (val.GetType()) {
    39. case rapidjson::kNumberType:
    40. cout << val.GetInt() << endl;
    41. break;
    42. case rapidjson::kStringType:
    43. cout << val.GetString() << endl;
    44. break;
    45. case rapidjson::kArrayType:
    46. for (rapidjson::Value::ValueIterator itr = val.GetArray().begin();
    47. itr != val.GetArray().end(); ++itr) {
    48. rapidjson::Value a;
    49. a = *itr;
    50. DfsDocument(std::move(a));
    51. }
    52. break;
    53. case rapidjson::kObjectType:
    54. for (rapidjson::Value::MemberIterator itr = val.GetObject().begin();
    55. itr != val.GetObject().end(); ++itr) {
    56. cout << itr->name.GetString() << " ";
    57. rapidjson::Value a;
    58. a = itr->value;
    59. DfsDocument(std::move(a));
    60. }
    61. default:
    62. break;
    63. }
    64. }

    运行结果

    这里需要注意: 

    object 类型json字符串中,“数字类型” 需转为 “字符串”,否则查询时会报错。

    7.  rapidjson 的其他使用方法

    1. /// <summary>
    2. /// json 属性
    3. /// </summary>
    4. void MyRapidJson::JsonAttribute()
    5. {
    6. rapidjson::Document doc;
    7. if (doc.Parse(strJson).HasParseError())
    8. {
    9. std::cout << "json 解析错误" << std::endl;
    10. return;
    11. }
    12. // 成员判断
    13. if (doc.HasMember("hobbys") && !doc["hobbys"].Empty())
    14. cout << "doc[\"hobbys\"] is not empty!" << "\n" << endl;
    15. else
    16. cout << "doc[\"hobbys\"] 不存在。" << "\n" << endl;
    17. //7.Array的大小
    18. if (doc["hobbys"].IsArray())
    19. {
    20. cout << "doc[\"hobbys\"].Capacity() = \" Array的容量及大小:\" " << doc["hobbys"].Capacity() << " 项" << endl;
    21. cout << "doc[\"hobbys\"].Size() = \" Array的容量及大小:\" " << doc["hobbys"].Size() << " 项" << endl;
    22. }
    23. // 字符串长度获取
    24. cout << doc["name"].GetString() <<" 字符串长度 :" << doc["name"].GetStringLength() << endl;
    25. //4.查询某个成员是否存在
    26. rapidjson::Value::MemberIterator iter = doc.FindMember("scores");
    27. if (iter != doc.MemberEnd())
    28. {
    29. cout << iter->name.GetString() << " : " << endl;
    30. DfsDocument(std::move(iter->value));
    31. }
    32. else
    33. cout << "Not Finded!" << endl;
    34. // 相同判断
    35. if (doc["name"].GetString() == string("MenAngel") &&
    36. doc["name"] == "MenAngel" &&
    37. strcmp(doc["name"].GetString(),"MenAngel") == 0)
    38. {
    39. cout << "判断为相等" << endl;
    40. }
    41. }

    运行结果:

  • 相关阅读:
    JavaScript之语法专题(类型转换,报错分析等)
    【力扣 Hot100 | 第七天】4.22(找到字符串中所有字母异位词)
    杂多酸离子液体[BMIM]3 PW12O40负载三乙烯四胺(TETA)功能化Fe3O4复合材料([BMIM]3 PW12O40/Fe3O4@TETA)
    通过HTTP发送大量数据的三种方法
    haproxy最强攻略
    python3.9 处理excel来实现类似excel中的vlookup功能
    【Typescript基础】函数详解
    〖Python网络爬虫实战㉕〗- Ajax数据爬取之Ajax 案例实战
    上门按摩小程序|同城上门按摩软件开发|上门按摩系统;
    Vue.js核心技术解析与uni-app跨平台实战开发学习笔记 第7章 Vue.js高级进阶 7.6 Vue计算属性
  • 原文地址:https://blog.csdn.net/chen1231985111/article/details/133342592