Third-party library Jsoncpp Read-write JSON

Source: Internet
Author: User

I. Summary

The full name of JSON is: JavaScript Object Notation, as the name implies, JSON is used to mark JavaScript objects, JSON is officially interpreted as: JSON is a lightweight data transmission format.

This article does not cover details of the JSON itself, but is intended to discuss how to use the C + + language to process JSON. More specific information about JSON can be found in the JSON website: http://www.json.org.

Second, this article chooses to process the JSON C + + library

This article selects a third-party library jsoncpp to parse the JSON. Jsoncpp is the more famous C + + JSON parsing library. In the JSON official website is also the most.

As: Http://sourceforge.net/projects/jsoncpp. The jsoncpp version used in this article is: 0.5.0.

Iii. compilation of Jsoncpp under Windows

To use a third-party repository, the first step is to compile, compile the source file into our convenient use of dynamic link library, static link library or static import library [1].

Jsconcpp JSON parsing source files are distributed under Include/json, Src/lib_json. In fact, Jsoncpp source is not many, in order to facilitate product management, there is no need to compile it as a dynamic link library or static import library, so we choose to use static link library [2].

Jsoncpp has been processed very well, all the compilation options have been configured, open Makefiles/vs71/jsoncpp.sln can start compiling (the default is to use the VS2003 compiler, open directly follow the VS2005 prompt conversion can be).

Iv. Jsoncpp use of the detailed

Jsoncpp mainly contains three types of Class:value, Reader, Writer. All objects in Jsoncpp, class names in namespace Json, contain json.h.

Json::value can only handle strings of ANSI type, and if the C + + program is Unicode encoded, it is best to add a Adapt class to fit.

1. Value

Json::value is the most basic and important class in jsoncpp, used to represent various types of objects, Jsoncpp supported object types are visible Json::valuetype enumeration values.

You can use the Json::value class as follows:

Json::value json_temp; Temporary object for use with the following code

json_temp["name"] = Json::value ("Huchao");

Json_temp["Age" = Json::value (26);

Json::value Root; Represents the entire JSON object

root["key_string"] = Json::value ("value_string"); Create a new Key (named: key_string) and give the string value: "Value_string".

root["Key_number"] = Json::value (12345); Create a new Key (named: key_number) and give the value: 12345.

root["Key_boolean"] = Json::value (false); Create a new Key (named: Key_boolean) and give the bool value: false.

root["key_double"] = Json::value (12.345); Create a new Key (named: key_double) and give the Double value: 12.345.

root["Key_object"] = json_temp; Create a new Key (named: key_object) to give the Json::value object value.

root["Key_array"].append ("array_string"); Create a new Key (named: key_array), type an array, and assign a value to the first element as a string: "Array_string".

root["Key_array"].append (1234); An array of key_array assignments, with the second element assigned a value of: 1234.

Json::valuetype type = Root.type (); Gets the type of root, here is the ObjectValue type.

Note: Unlike C + +, JavaScript arrays can be any type of value, so jsoncpp is also possible.

As the previous usage has been able to meet most of the JSON application, of course, there are some other jsoncpp, such as setting comments, comparing JSON size, exchanging JSON objects, etc., are easy to use, let's try it yourself.

2. Writer

As mentioned on the use of Json::value, now it is time to view the contents of the assignment, to view the Json content, using the Writer class.

The Json::writer class of Jsoncpp is a pure virtual class and cannot be used directly. Here we use Json::writer subclasses: Json::fastwriter, Json::styledwriter, Json::styledstreamwriter.

As the name implies, using Json::fastwriter to deal with Json should be the fastest, let's try.

Json::fastwriter Fast_writer;

Std::cout << fast_writer.write (root) << Std::endl;

The output is:

{"Key_array": ["array_string", 1234], "Key_boolean": false, "key_double": 12.3450, "Key_number": 12345, "Key_object": {" Age ": +," name ":" Huchao "}," key_string ":" Value_string "}

Again as the name implies, with Json::styledwriter is formatted Json, below we see how json::styledwriter is formatted.

Json::styledwriter Styled_writer;

Std::cout << styled_writer.write (root) << Std::endl;

The output is:

{

"Key_array": ["array_string", 1234],

"Key_boolean": false,

"Key_double": 12.3450,

"Key_number": 12345,

"Key_object": {

"Age": 26,

"Name": "Huchao"

},

"Key_string": "Value_string"

}

3. Reader

Json::reader is used to read, say the exact point, is used to convert the string to the Json::value object, let's look at a simple example.

Json::reader Reader;

Json::value Json_object;

Const char* json_document = "{\" age\ ": 26,\" name\ ": \" huchao\ "}";

if (!reader.parse (Json_document, Json_object))

return 0;

Std::cout << json_object["name"] << Std::endl;

Std::cout << json_object["age"] << Std::endl;

The output is:

"Huchao"

Test Example:

[Plain]View PlainCopy
  1. #include <iostream>
  2. #include <sstream>
  3. #include <exception>
  4. #include "jsoncpp.hpp"
  5. int main (int argc, char * * argv) {
  6. Json::value Root,task1,task2;
  7. //////////////////////////////////
  8. Encoding test
  9. /////////////////////////////////
  10. task1["int"] = 123456;
  11. task1["Double"] = 99.88;
  12. Task1["string"] = "AAA";
  13. task1["bool"] = true;
  14. task2["int"] = 222222;
  15. task2["Double"] = 77.88;
  16. Task2["string"] = "BBB";
  17. task1["bool"] = false;
  18. root["resource"] = "/TASKS/29";
  19. Root["method"] = "GET";
  20. List of 2 tasks
  21. root["Body"][0] = Task1;
  22. root["Body"][1] = Task2;
  23. Std::ostringstream OSTRM;
  24. ostrm<<root;
  25. Std::cout<<ostrm.str () <<std::endl;
  26. //////////////////////////////////
  27. Decoding test
  28. /////////////////////////////////
  29. std::string content (Ostrm.str ());
  30. Std::istringstream ISTRM (content);
  31. Json::value root1;
  32. istrm>>root1;
  33. std::cout<<root1["Body"]<<std::endl;
  34. Try to decode a non-exist key
  35. if (root1["body"][0]["string1"] = = Json::nullvalue)
  36. std::cout<< "not found string1" <<std::endl;
  37. Invalid structure
  38. try {
  39. std::cout<<root1["Body" ["not List"] ["string"].asdouble () <<std::endl;
  40. } catch (Std::exception & ex) {
  41. std::cout<< "!!!!" <<ex.what () <<std::endl;
  42. }
  43. Fail to decode a invalid double field, and get an exception
  44. try {
  45. std::cout<<root1["Body"][1]["string"].asdouble () <<std::endl;
  46. } catch (Std::exception & ex) {
  47. std::cout<< "!!!!" <<ex.what () <<std::endl;
  48. }
  49. Normally decoding
  50. std::cout<< "Get double:" <<root1["Body"][1]["double"].asdouble () <<std::endl;
  51. std::cout<< "Get double:" <<root1["Body"][0]["bool"].asbool () <<std::endl;
  52. return 0;
  53. }

Append traversal:

[Plain]View PlainCopy
    1. for (int i=0;i<root1["Body"].size (); i++) {
    2. std::cout<< "Body:" <<i<< "<<root1[" Body "][i][" double "]<<std::endl;
    3. std::cout<< "Body:" <<i<< "<<root1[" Body "][i][" int "]<<std::endl;
    4. }



26

As you can see, the above code has parsed out the JSON string.

Note: The Jason Library is primarily used in projects to convert protocol data into inter-network text protocols and interact with the server.

--------------------------------------

[1]: The simplest way to use third-party source code is to directly add files to the project, but this is not conducive to the source code, software Product management, for general software development, is not recommended for use.

[2]: If you really need to compile into a dynamic link library, static import library, you can use VS create a new project properties, and then in project-to-properties to set the appropriate settings.

This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/xt_xiaotian/archive/2010/06/04/5648388.aspx

Third-party library Jsoncpp Read-write JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.