小言_互联网的博客

Linux(程序设计):31---jsoncpp库(C++操作JSON)

550人阅读  评论(0)

一、jsoncpp库概述

库的安装

sudo apt-get install libjsoncpp-dev

  • 安装完成之后,头文件默认安装在/usr/include/jsoncpp/json/目录下,库API文档默认在/usr/share/doc/libjsoncpp-dev/目录下

编译带有jsoncpp库的C++程序

  • 使用如下的命令进行编译,编译时带上-ljsoncpp选项即可
  • 例如:
g++ jsoncpp_demo01.c -o demo01 -ljsoncpp -std=c++11

二、jsoncpp支持的值

  • jsoncpp 使用 Json::Value 对象来保存 JSON 串,Json::Value 对象可以表示如下数据类 型:

三、相关接口

检测保存的数据类型


   
  1. bool isNull() const;
  2. bool isBool() const;
  3. bool isInt() const;
  4. bool isInt64() const;
  5. bool isUInt() const;
  6. bool isUInt64() const;
  7. bool isIntegral() const;
  8. bool isDouble() const;
  9. bool isNumeric() const;
  10. bool isString() const;
  11. bool isArray() const;
  12. bool isObject() const;

基础数据类型的访问


   
  1. const char* asCString() const;
  2. JSONCPP_STRING asString() const;
  3. Int asInt() const;
  4. UInt asUInt() const;
  5. Int64 asInt64() const;
  6. UInt64 asUInt64() const;
  7. LargestInt asLargestInt() const;
  8. LargestUInt asLargestUInt() const;
  9. float asFloat() const;
  10. double asDouble() const;
  11. bool asBool() const;

数组风格

  • ValueType::arrayValue 和 ValueType::objectValue 数据类型的访问,操作方式很类似 C++的 vector,可以使用数组风格或者迭代器风格来操作数据。例如:
root["name"] = "milo";
  • 下面是相关接口

   
  1. ArrayIndex size() const;
  2. Value& operator[](ArrayIndex index);
  3. Value& operator[](int index);
  4. const Value& operator[](ArrayIndex index) const;
  5. const Value& operator[](int index) const;
  6. Value get(ArrayIndex index, const Value& defaultValue) const;
  7. const_iterator begin() const;
  8. const_iterator end() const;
  9. iterator begin();
  10. iterator end();
  • ValueType::objectValue 数据类型的访问,操作方式很类似 C++的 map

   
  1. Value& operator[]( const char* key);
  2. const Value& operator[]( const char* key) const;
  3. Value& operator[]( const JSONCPP_STRING& key);
  4. const Value& operator[]( const JSONCPP_STRING& key) const;
  5. Value& operator[]( const StaticString& key);
  6. Value& operator[]( const CppTL::ConstString& key);
  7. const Value& operator[]( const CppTL::ConstString& key) const;
  8. Value get(const char* key, const Value& defaultValue) const;
  9. Value get(const char* begin, const char* end, const Value& defaultValue) const;
  10. Value get(const JSONCPP_STRING& key, const Value& defaultValue) const;
  11. Value get(const CppTL::ConstString& key, const Value& defaultValue) const;

修改数据

  • 知道如何获取 Json::Value 对象或其子对象后,我们来看下如何修改 Json::Value 保存 的数据:
  • 直接使用=赋值就可以了
Value& operator=(Value other);
  • 因为 Json::Value 已经实现了各种数据类型的构造函数

   
  1. Value(ValueType type = nullValue);
  2. Value(Int value);
  3. Value(UInt value);
  4. Value(Int64 value);
  5. Value(UInt64 value);
  6. Value( double value);
  7. Value( const char* value);
  8. Value( const char* begin, const char* end);
  9. Value( const StaticString& value);
  10. Value( const JSONCPP_STRING& value);
  11. Value( const CppTL::ConstString& value);
  12. Value( bool value);
  13. Value( const Value& other);
  14. Value(Value&& other);

四、注意事项

类型转换

  • 对于Int、Uint、Int64、UInt64等类型,注意类型。
root["age"] = 80;  //默认为Int类型
  • 可以使用下面的方式进行强制类型转换
root["age"] = (Json::Uint)80;

空值

  • 如果要将变量设置为 null,应该使用如下的方式
root["address"] = Json::nullValue;

五、演示案例1

代码如下


   
  1. #include <iostream>
  2. #include <string>
  3. #include <jsoncpp/json/json.h>
  4. int main()
  5. {
  6. std:: cout << "Hello World!" << std:: endl;
  7. Json::Value root;
  8. Json::FastWriter fast;
  9. root[ "ModuleType"] = Json::Value( 1);
  10. root[ "ModuleCode"] = Json::Value( "China");
  11. std:: cout<<fast.write(root)<< std:: endl;
  12. Json::Value sub;
  13. sub[ "version"] = Json::Value( "1.0");
  14. sub[ "city"] = Json::Value(root);
  15. fast.write(sub);
  16. std:: cout<<sub.toStyledString()<< std:: endl;
  17. return 0;
  18. }
  • 编译运行如下: 
g++ jsoncpp_demo01.c -o demo01 -ljsoncpp -std=c++11

六、演示案例2

代码如下


   
  1. #include <string>
  2. #include <jsoncpp/json/json.h>
  3. #include <iostream>
  4. using namespace std;
  5. void readJson() {
  6. std:: string strValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}";
  7. Json::Reader reader;
  8. Json::Value value;
  9. if (reader.parse(strValue, value))
  10. {
  11. std:: string out = value[ "name"].asString();
  12. std:: cout << out << std:: endl;
  13. const Json::Value arrayObj = value[ "array"];
  14. for ( unsigned int i = 0; i < arrayObj.size(); i++)
  15. {
  16. if (!arrayObj[i].isMember( "cpp"))
  17. continue;
  18. out = arrayObj[i][ "cpp"].asString();
  19. std:: cout << out;
  20. if (i != (arrayObj.size() - 1))
  21. std:: cout << std:: endl;
  22. }
  23. }
  24. }
  25. void writeJson() {
  26. Json::Value root;
  27. Json::Value arrayObj;
  28. Json::Value item;
  29. item[ "cpp"] = "jsoncpp";
  30. item[ "java"] = "jsoninjava";
  31. item[ "php"] = "support";
  32. arrayObj.append(item);
  33. root[ "name"] = "json";
  34. root[ "array"] = arrayObj;
  35. root.toStyledString();
  36. std:: string out = root.toStyledString();
  37. std:: cout << out << std:: endl;
  38. }
  39. int main(int argc, char** argv) {
  40. readJson();
  41. writeJson();
  42. return 0;
  43. }
  • 编译运行如下:  
g++ jsoncpp_demo02.c -o demo02 -ljsoncpp -std=c++11

七、演示案例3

代码如下


   
  1. //测试jsoncpp的使用方法和性能
  2. #include <memory>
  3. #include <sstream>
  4. #include <iostream>
  5. #include <stdint.h>
  6. #include <unistd.h>
  7. #include <sys/time.h>
  8. #include <sys/wait.h>
  9. #include "jsoncpp/json/json.h"
  10. #include "jsoncpp/json/value.h"
  11. #include "jsoncpp/json/reader.h"
  12. #include "jsoncpp/json/writer.h"
  13. /*
  14. {
  15. "name": "milo",
  16. "age": 80,
  17. "languages": ["C++", "C"],
  18. "phone": {
  19. "number": "186****3143",
  20. "type": "home"
  21. },
  22. "books":[
  23. {
  24. "name": "Linux kernel development",
  25. "price":7.7
  26. },
  27. {
  28. "name": "Linux server development",
  29. "price": 8.0
  30. }
  31. ],
  32. "vip":true,
  33. "address": null
  34. }
  35. */
  36. static uint64_t getNowTime()
  37. {
  38. struct timeval tval;
  39. uint64_t nowTime;
  40. gettimeofday(&tval, NULL);
  41. nowTime = tval.tv_sec * 1000L + tval.tv_usec / 1000L;
  42. return nowTime;
  43. }
  44. std:: string JsoncppEncodeNew()
  45. {
  46. std:: string jsonStr;
  47. // 一个value是可以包含多个键值对
  48. Json::Value root, languages, phone, book, books;
  49. // 姓名
  50. root[ "name"] = "milo";
  51. // 年龄
  52. root[ "age"] = 80;
  53. // 语言
  54. languages[ 0] = "C++";
  55. languages[ 1] = "Java";
  56. root[ "languages"] = languages;
  57. // 电话
  58. phone[ "number"] = "186****3143";
  59. phone[ "type"] = "home";
  60. root[ "phone"] = phone;
  61. // 书籍
  62. book[ "name"] = "Linux kernel development";
  63. book[ "price"] = 7.7;
  64. books[ 0] = book; // 深拷贝
  65. book[ "name"] = "Linux server development";
  66. book[ "price"] = 8.0;
  67. books[ 1] = book; // 深拷贝
  68. root[ "books"] = books;
  69. // 是否为vip
  70. root[ "vip"] = true;
  71. // address信息空null
  72. root[ "address"] = "yageguoji";
  73. Json::StreamWriterBuilder writerBuilder;
  74. std:: ostringstream os;
  75. std:: unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
  76. jsonWriter->write(root, &os);
  77. jsonStr = os.str();
  78. // std::cout << "Json:\n" << jsonStr << std::endl;
  79. return jsonStr;
  80. }
  81. std:: string JsoncppEncodeOld()
  82. {
  83. std:: string jsonStr;
  84. Json::Value root, languages, phone, book, books;
  85. // 姓名
  86. root[ "name"] = "milo";
  87. //root["name"] = Json::nullValue;
  88. // 年龄
  89. root[ "age"] = 80;
  90. // 语言
  91. languages[ 0] = "C++";
  92. languages[ 1] = "Java";
  93. root[ "languages"] = languages;
  94. // 电话
  95. phone[ "number"] = "186****3143";
  96. phone[ "type"] = "home";
  97. root[ "phone"] = phone;
  98. // 书籍
  99. book[ "name"] = "Linux kernel development";
  100. book[ "price"] = ( float) 7.7;
  101. books[ 0] = book;
  102. book[ "name"] = "Linux server development";
  103. book[ "price"] = ( float) 8.0;
  104. books[ 1] = book;
  105. root[ "books"] = books;
  106. // 是否为vip
  107. root[ "vip"] = true;
  108. // address信息空null
  109. root[ "address"] = "yageguoji"; //;// Json::nullValue; // 如果是null,则要用自定义的Json::nullValue,不能用NULL
  110. Json::FastWriter writer;
  111. jsonStr = writer.write(root);
  112. // std::cout << "Json:\n" << jsonStr << std::endl;
  113. return jsonStr;
  114. }
  115. // 不能返回引用
  116. Json:: Value JsoncppEncodeOldGet()
  117. {
  118. Json::Value root;
  119. Json::Value languages, phone, book, books;
  120. // 姓名
  121. root[ "name"] = "milo";
  122. //root["name"] = Json::nullValue;
  123. // 年龄
  124. root[ "age"] = 80;
  125. // 语言
  126. languages[ 0] = "C++";
  127. languages[ 1] = "Java";
  128. root[ "languages"] = languages;
  129. // 电话
  130. phone[ "number"] = "186****3143";
  131. phone[ "type"] = "home";
  132. root[ "phone"] = phone;
  133. // 书籍
  134. book[ "name"] = "Linux kernel development";
  135. book[ "price"] = ( float) 7.7;
  136. books[ 0] = book;
  137. book[ "name"] = "Linux server development";
  138. book[ "price"] = ( float) 8.0;
  139. books[ 1] = book;
  140. root[ "books"] = books;
  141. // 是否为vip
  142. root[ "vip"] = true;
  143. // address信息空null
  144. root[ "address"] = Json::nullValue; //"yageguoji";// Json::nullValue; // 如果是null,则要用自定义的Json::nullValue,不能用NULL
  145. std:: cout << "JsoncppEncodeOldGet:\n" << std:: endl;
  146. return root;
  147. }
  148. void printJsoncpp(Json::Value &root)
  149. {
  150. if(root[ "name"].isNull())
  151. {
  152. std:: cout << "name null\n";
  153. }
  154. std:: cout << "name: " << root[ "name"].asString() << std:: endl;
  155. std:: cout << "age: " << root[ "age"].asInt() << std:: endl;
  156. Json::Value &languages = root[ "languages"];
  157. std:: cout << "languages: ";
  158. for ( uint32_t i = 0; i < languages.size(); ++i)
  159. {
  160. if (i != 0)
  161. {
  162. std:: cout << ", ";
  163. }
  164. std:: cout << languages[i].asString();
  165. }
  166. std:: cout << std:: endl;
  167. Json::Value &phone = root[ "phone"];
  168. std:: cout << "phone number: " << phone[ "number"].asString() << ", type: " << phone[ "type"].asString() << std:: endl;
  169. Json::Value &books = root[ "books"];
  170. for ( uint32_t i = 0; i < books.size(); ++i)
  171. {
  172. Json::Value &book = books[i];
  173. std:: cout << "book name: " << book[ "name"].asString() << ", price: " << book[ "price"].asFloat() << std:: endl;
  174. }
  175. std:: cout << "vip: " << root[ "vip"].asBool() << std:: endl;
  176. if (!root[ "address"].isNull())
  177. {
  178. std:: cout << "address: " << root[ "address"].asString() << std:: endl;
  179. }
  180. else
  181. {
  182. std:: cout << "address is null" << std:: endl;
  183. }
  184. }
  185. bool JsoncppDecodeNew(const std::string &info)
  186. {
  187. if (info.empty())
  188. return false;
  189. bool res;
  190. JSONCPP_STRING errs;
  191. Json::Value root;
  192. Json::CharReaderBuilder readerBuilder;
  193. std:: unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
  194. res = jsonReader->parse(info.c_str(), info.c_str() + info.length(), &root, &errs);
  195. if (!res || !errs.empty())
  196. {
  197. std:: cout << "parseJson err. " << errs << std:: endl;
  198. return false;
  199. }
  200. // printJsoncpp(root);
  201. return true;
  202. }
  203. bool JsoncppDecodeOld(const std::string &strJson)
  204. {
  205. if (strJson.empty())
  206. return false;
  207. bool res;
  208. Json::Value root;
  209. Json::Reader jsonReader;
  210. res = jsonReader.parse(strJson, root);
  211. if (!res)
  212. {
  213. std:: cout << "jsonReader.parse err. " << std:: endl;
  214. return false;
  215. }
  216. // printJsoncpp(root);
  217. return true;
  218. }
  219. const char *strCjson = "{ \
  220. \"name\": \"milo\", \
  221. \"age\": 80, \
  222. \"languages\": [\"C++\", \"C\"],\
  223. \"phone\": { \
  224. \"number\": \"186****3143\", \
  225. \"type\": \"home\" \
  226. }, \
  227. \"books\": [{ \
  228. \"name\": \"Linux kernel development\", \
  229. \"price\": 7.700000 \
  230. }, { \
  231. \"name\": \"Linux server development\", \
  232. \"price\": 8 \
  233. }], \
  234. \"vip\": true, \
  235. \"address\": null \
  236. } \
  237. ";
  238. #define TEST_COUNT 100000
  239. int main()
  240. {
  241. std:: string jsonStrNew;
  242. std:: string jsonStrOld;
  243. jsonStrNew = JsoncppEncodeNew();
  244. // JsoncppEncodeNew size: 337
  245. std:: cout << "JsoncppEncodeNew size: " << jsonStrNew.size() << std:: endl;
  246. std:: cout << "JsoncppEncodeNew string: " << jsonStrNew << std:: endl;
  247. JsoncppDecodeNew(jsonStrNew);
  248. jsonStrOld = JsoncppEncodeOld();
  249. // JsoncppEncodeOld size: 248
  250. std:: cout << "\n\nJsoncppEncodeOld size: " << jsonStrOld.size() << std:: endl;
  251. std:: cout << "JsoncppEncodeOld string: " << jsonStrOld << std:: endl;
  252. JsoncppDecodeOld(jsonStrOld);
  253. Json::Value root = JsoncppEncodeOldGet();
  254. Json::FastWriter writer;
  255. std:: cout << "writer:\n" << std:: endl;
  256. std:: string jsonStr = writer.write(root);
  257. std:: cout << "\n\njsonStr string: " << jsonStrOld << std:: endl;
  258. #if 1
  259. uint64_t startTime;
  260. uint64_t nowTime;
  261. startTime = getNowTime();
  262. std:: cout << "jsoncpp encode time testing" << std:: endl;
  263. for( int i = 0; i < TEST_COUNT; i++)
  264. {
  265. JsoncppEncodeNew();
  266. }
  267. nowTime = getNowTime();
  268. std:: cout << "jsoncpp encode " << TEST_COUNT << " time, need time: "
  269. << nowTime-startTime << "ms" << std:: endl;
  270. startTime = getNowTime();
  271. std:: cout << "\njsoncpp encode time testing" << std:: endl;
  272. for( int i = 0; i < TEST_COUNT; i++)
  273. {
  274. JsoncppEncodeOld();
  275. }
  276. nowTime = getNowTime();
  277. std:: cout << "jsoncpp encode " << TEST_COUNT << " time, need time: "
  278. << nowTime-startTime << "ms" << std:: endl;
  279. startTime = getNowTime();
  280. std:: cout << "\njsoncpp decode time testing" << std:: endl;
  281. for( int i = 0; i < TEST_COUNT; i++)
  282. {
  283. JsoncppDecodeNew(jsonStrNew);
  284. }
  285. nowTime = getNowTime();
  286. std:: cout << "jsoncpp decode " << TEST_COUNT << " time, need time: "
  287. << nowTime-startTime << "ms" << std:: endl;
  288. startTime = getNowTime();
  289. std:: cout << "\njsoncpp decode time testing" << std:: endl;
  290. for( int i = 0; i < TEST_COUNT; i++)
  291. {
  292. JsoncppDecodeOld(jsonStrNew);
  293. }
  294. nowTime = getNowTime();
  295. std:: cout << "jsoncpp decode " << TEST_COUNT << " time, need time: "
  296. << nowTime-startTime << "ms" << std:: endl;
  297. #endif
  298. return 0;
  299. }
  • 编译运行如下:  
g++ jsoncpp_speed.cpp -o jsoncpp_speed -ljsoncpp -std=c++11

 


转载:https://blog.csdn.net/qq_41453285/article/details/106725261
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场