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
- #include <iostream>
- #include <sstream>
- #include <exception>
- #include "jsoncpp.hpp"
- int main (int argc, char * * argv) {
- Json::value Root,task1,task2;
- //////////////////////////////////
- Encoding test
- /////////////////////////////////
- task1["int"] = 123456;
- task1["Double"] = 99.88;
- Task1["string"] = "AAA";
- task1["bool"] = true;
- task2["int"] = 222222;
- task2["Double"] = 77.88;
- Task2["string"] = "BBB";
- task1["bool"] = false;
- root["resource"] = "/TASKS/29";
- Root["method"] = "GET";
- List of 2 tasks
- root["Body"][0] = Task1;
- root["Body"][1] = Task2;
- Std::ostringstream OSTRM;
- ostrm<<root;
- Std::cout<<ostrm.str () <<std::endl;
- //////////////////////////////////
- Decoding test
- /////////////////////////////////
- std::string content (Ostrm.str ());
- Std::istringstream ISTRM (content);
- Json::value root1;
- istrm>>root1;
- std::cout<<root1["Body"]<<std::endl;
- Try to decode a non-exist key
- if (root1["body"][0]["string1"] = = Json::nullvalue)
- std::cout<< "not found string1" <<std::endl;
- Invalid structure
- try {
- std::cout<<root1["Body" ["not List"] ["string"].asdouble () <<std::endl;
- } catch (Std::exception & ex) {
- std::cout<< "!!!!" <<ex.what () <<std::endl;
- }
- Fail to decode a invalid double field, and get an exception
- try {
- std::cout<<root1["Body"][1]["string"].asdouble () <<std::endl;
- } catch (Std::exception & ex) {
- std::cout<< "!!!!" <<ex.what () <<std::endl;
- }
- Normally decoding
- std::cout<< "Get double:" <<root1["Body"][1]["double"].asdouble () <<std::endl;
- std::cout<< "Get double:" <<root1["Body"][0]["bool"].asbool () <<std::endl;
- return 0;
- }
Append traversal:
[Plain]View PlainCopy
- for (int i=0;i<root1["Body"].size (); i++) {
- std::cout<< "Body:" <<i<< "<<root1[" Body "][i][" double "]<<std::endl;
- std::cout<< "Body:" <<i<< "<<root1[" Body "][i][" int "]<<std::endl;
- }
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