JSON is a lightweight data-definition format, and it's a good choice to use for data exchange compared to XML, which is easy to learn, and not much worse than XML.
The full name of JSON is: JavaScript Object notation, as the name suggests, JSON is used to mark JavaScript objects, and details refer to http://www.json.org/.
This article selects the third party library Jsoncpp to parse Json,jsoncpp is the more famous C + + analytic library, in the JSON official website is also the most notable.
Jsoncpp Introduction
Jsoncpp consists of three types of Class:value Reader Writer.
All objects in Jsoncpp, class names in namespace json, contain json.h.
Note: Json::value can only handle ANSI-type strings, and if the C + + program uses Unicode encoding, it is best to add a adapt class to fit.
Download and compile
The operating environment of this article is: Redhat 5.5 + g++version 4.6.1 + GNU make 3.81 + jsoncpp-0.5.0
Download address is: http://sourceforge.net/projects/jsoncpp/
After decompression get jsoncpp-src-0.5.0 folder, we only need Jsoncpp header file and CPP file, where Jsonscpp header file is located in Jsoncpp-src-0.5.0includejson, The Jsoncpp CPP file is located in Jsoncpp-src-0.5.0srclib_json.
Here I list our working directory:
jsoncpp///working directory
| |--INCLUDE//header file root directory
| |--JSON//json header file, corresponding to Jsoncpp-src-0.5.0includejson
|--src//cpp source file root directory
|--JSON//jsoncpp source file, corresponding to Jsoncpp-src-0.5.0srclib_json
|--main.cpp//Our main function, call Jsoncpp sample code
|--Makefile//makefile, do not let us say more, do not understand please see my blog makefile best Practice
Deserialize a JSON object
Suppose you have a JSON object as follows:
{"Name": "Json″," array: [{"CPP": "Jsoncpp"}, {"Java": "Jsoninjava"}, {"PHP": "Support"}] }
We want to implement this JSON's reverse sequence code as follows:
Voidreadjson () {usingnamespacestd; Std::stringstrvalue = "{\ name\": \ "json\", \ "array\": [{\ "cpp\": \ "Jsoncpp\"},{\ "java\": \ "Jsoninjava\"},{\ "php\": \ " Support\ "}]}"; Json::reader Reader; Json::value Value; if (Reader.parse (strvalue, value)) {std::stringout= value["name"].asstring (); Std::cout <<out<<std::endl; Constjson::value arrayobj = value["Array"]; for (unsigned inti = 0;i <arrayobj.size (); i++) {if (!arrayobj[i].ismember ("CPP")) continue; out= arrayobj[i]["CPP"].asstring (); Std::cout <<out; if (I!= (Arrayobj.size ()-1)) Std::cout <<std::endl; } } }
Serialization of JSON objects
Voidwritejson () { USINGNAMESPACESTD json::value root; json::value arrayobj; json::value item; item["cpp"] = "Jsoncpp"; item["java"] = "Jsoninjava"; item["PHP"] = "support"; Arrayobj.append (item); root["name"] = "JSON"; root["Array"] = arrayobj; Root.tostyledstring (); Std::stringout= root.tostyledstring (); std::cout <<out<<std::endl; }