JSON封装(C++)

本文主要介绍使用 jsoncpp 库,编写C++语言的 JSON 封装程序。

1 示例程序

1.1 封装普通的json结构

示例代码(json_create_test1.cpp)如下:

 
  1. #include <iostream>

  2. #include <string>

  3. #include <jsoncpp/json/json.h>

  4.  
  5. using namespace std;

  6.  
  7. int main()

  8. {

  9. Json::Value root;

  10. string strJsonMsg;

  11.  
  12. // 字符串类型

  13. root["occupation"] = "paladin";

  14. // 布尔类型

  15. root["valid"] = true;

  16. // 数字类型

  17. root["role_id"] = 1;

  18.  
  19. // 将json转换为string类型

  20. strJsonMsg = root.toStyledString();

  21.  
  22. cout<< "strJsonMsg is: " << strJsonMsg << endl;

  23.  
  24. return 0;

  25. }

  26.  

编译并执行上述代码,结果如下:

从上述执行结果能够看到,我们成功地创建了一个json结构。

1.2 封装带有数组的json结构

示例代码(json_array_create.cpp)如下:

 
  1. #include <iostream>

  2. #include <string>

  3. #include <jsoncpp/json/json.h>

  4.  
  5. using namespace std;

  6.  
  7. int main()

  8. {

  9. Json::Value root;

  10. Json::Value ArrayObj;

  11. Json::Value ArrayItem1;

  12. Json::Value ArrayItem2;

  13. string strJsonMsg;

  14.  
  15. // 1. 添加数组外数据

  16. root["type"] = "roles_msg";

  17. root["valid"] = true;

  18.  
  19. // 2. 编写数组内容

  20. ArrayItem1["role_id"] = 1;

  21. ArrayItem1["occupation"] = "paladin";

  22. ArrayItem1["camp"] = "alliance";

  23. ArrayObj.append(ArrayItem1);

  24.  
  25. ArrayItem2["role_id"] = 2;

  26. ArrayItem2["occupation"] = "Mage";

  27. ArrayItem2["camp"] = "alliance";

  28. ArrayObj.append(ArrayItem2);

  29.  
  30. // 3. 添加数组数据

  31. root["list"] = ArrayObj;

  32.  
  33. // 将json转换为string类型

  34. strJsonMsg = root.toStyledString();

  35.  
  36. cout<< "strJsonMsg is: " << endl << strJsonMsg << endl;

  37.  
  38. return 0;

  39. }

  40.  

编译并执行上述代码,结果如下:

从上述执行结果能够看到,我们成功地创建了一个带有数组的json结构。

--------------------- 本文来自 liitdar 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/liitdar/article/details/81669446?utm_source=copy

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值