C + + reads and writes JSON files through the Jsoncpp class library

Source: Internet
Author: User
Tags parse error

JSON is a lightweight data definition format, easy to learn and use than XML, and the extension is not much worse than XML, data exchange is a good choice. The full name of JSON is: JavaScript Object Notation, as the name implies, JSON is used to mark JavaScript objects, the details refer to http://www.json.org/.


This tutorial chooses third-party library jsoncpp to parse JSON, Jsoncpp is a more famous C + + analytic library, which is also the most popular in the JSON website.


jsoncpp:http://download.csdn.net/detail/tennysonsky/


After downloading the source code to extract the jsoncpp-src-0.5.0 folder, we only need jsoncpp header files and CPP files, where Jsonscpp header files are located in Jsoncpp-src-0.5.0\include\json, The Jsoncpp CPP file is located in Jsoncpp-src-0.5.0\src\lib_json.


JSON: The header file required for JSON operation, this folder name cannot be modified because the. cpp in the Lib_json directory contains the header file form: #include <json/xxx.h>.


Lib_json: The CPP file required for JSON operation, the name of this folder can be named according to your needs.

Copy the JSON and Lib_json into the directory where you need to write the code ( Note : JSON and Lib_json are in the same level directory ):



When compiling the code, the CPP file in the Lib_json directory needs to be added to the compilation condition:



1) Read JSON from the string

#include <string> #include <json/json.h> #include <iostream> #include <fstream>using namespace Std;void Readstrjson (); Reads the jsonvoid Readstrprojson () from the string; Read JSON from string (more complex) int main (int argc, char *argv[]) {Readstrjson (); cout << "\ n"; Readstrprojson (); return 0;} Read from String jsonvoid Readstrjson () {//string const char* str = "{\" praenomen\ ": \" gaius\ ", \" nomen\ ": \" julius\ ", \" cognomen\        ": \" Caezar\ "," "\" born\ ": -100,\" died\ ":-44}"; /*//json content as follows: {"praenomen": "Gaius", "nomen": "Julius", "cognomen": "Caezar", "Born": -100, "died": -44} */Json::reader  Reader  Json::value Root;      Read data from String if (Reader.parse (Str,root)) {string praenomen = root["praenomen"].asstring ();      string nomen = root["nomen"].asstring ();      String cognomen = root["cognomen"].asstring ();      int born = root["Born"].asint ();      int died = root["died"].asint (); cout << praenomen + "" + nomen + "" + cognomen << "is born in year" << BorN << ", died in year" << died << Endl; }//read JSON from string (more complex) void Readstrprojson () {string strvalue = "{\" name\ ": \" json\ ", \" array\ ": [{\" cpp\ ": \" Jsoncpp\ "} {\ "java\": \ "Jsoninjava\"},{\ "php\": \ "Support\"}]} ";/*//json content is as follows: {" name ":" Json″, "" Array ": [{" C    PP ":" Jsoncpp "}, {" Java ":" Jsoninjava "}, {" PHP ":" Support "} ]}*/json::reader Reader; Json::value value;if (Reader.parse (strvalue, Value)) {string out = value[' name '].asstring () cout << out << Endl;const json::value arrayobj = value["Array"];for (unsigned int i = 0; i < arrayobj.size (); i++) {if (!arrayobj[i].is Member ("CPP")) Continue;out = arrayobj[i]["cpp"].asstring () cout << out;if (i! = (Arrayobj.size ()-1)) cout <&lt ; Endl;}}}

The results of the compilation run are as follows:



2) Read JSON from the file

#include <string> #include <json/json.h> #include <iostream> #include <fstream>using namespace Std;void Readfilejson (); Read JSON from the file, a file that stores the JSON format string int main (int argc, char *argv[]) {Readfilejson (); return 0;} Read Jsonvoid Readfilejson () {Json::reader reader from the file; Json::value root;//read from the file to ensure that the current file has Test.json file Ifstream in ("Test.json", ios::binary);//in.open ("Test.json", iOS:: binary); if (!in.is_open ()) {cout << "Error opening file\n"; return;} The/*//test.json contents are as follows: {"name": "Tsybius", "age": All, "Sex_is_male": true, "partner": {"Partner_name": "Galatea", "Partner_ Age ": +," Partner_sex_is_male ": false}," Achievement ": [" Ach1 "," Ach2 "," Ach3 "]}*/if (Reader.parse (in,root)) {// Read the root node information string name = root["Name"].asstring (); int = root["Age"].asint (); bool Sex_is_male = root["Sex_is_male"]. Asbool () cout << "My name is" << name << endl;cout << "I ' m" << age << "years old" & lt;< endl;cout << "I ' m A" << (Sex_is_male? ") Man ":" Woman ") << endl;//read child node information string partner_name = root["partner" ["Partner_name"].asstring (); int partner_age = root["partner"] ["Partner_age"].asint (); bool Partner_sex_is_male = root["partner" ["Partner_sex_is_male"].asbool (); cout << " My Partner ' s name is ' << partner_name << endl;cout << (partner_sex_is_male? " He ":" she ") <<" is "<< partner_age <<" years old "<< endl;//read array information cout <<" Here's my Achi Evements: "<< endl;for (unsigned int i = 0; I < root["Achievement"].size (); i++) {String ach = root["achievement"][i].asstring (); cout << ach << ' \ t ';} cout << endl;cout << "Reading complete!" << Endl;} Else{cout << "Parse error\n" << Endl;} In.close ();}

The contents of the Test.json file are as follows:

{"Name": "Mike Jiang", "age": +, "Sex_is_male": true, "partner": {    "partner_name": "Galatea",    "Partner_age": 21 ,    "Partner_sex_is_male": false}, "Achievement": ["Ach1", "Ach2", "Ach3"]}

The results of the compilation run are as follows:



3) Save the information in JSON format

#include <string> #include <json/json.h> #include <iostream> #include <fstream>using namespace Std;void Writefilejson ();//Save the information in JSON format int main (int argc, char *argv[]) {Writefilejson (); return 0;} Save information in Json format void Writefilejson () {///root node Json::value root;//root node property root["Name"] = Json::value ("Mike Jiang"); root["Age" ] = Json::value (root["sex_is_male"] = Json::value (TRUE);//child node Json::value partner;//child node Property partner["Partner_name"] = Json::value ("Galatea");p artner["partner_age"] = Json::value (+);p artner["Partner_sex_is_male"] = Json::value ( FALSE);//The child node is hung on the root node root["partner"] = Json::value (partner);//Array Form root["Achievement"].append ("Ach1"); root[" Achievement "].append (" Ach2 ") root[" Achievement "].append (" Ach3 ");//Direct output cout <<" Fastwriter: "<< Endl; Json::fastwriter fw;cout << fw.write (root) << Endl << endl;//indent output cout << "Styledwriter:" < < Endl; Json::styledwriter sw;cout << sw.write (root) << Endl << endl;//output to file Ofstream Os;os. Open ("Demo.json"); OS << sw.write (root); Os.close ();/*//json file contents are as follows: {"Achievement": ["Ach1", "Ach2", "Ach3"], " Age ":", "name": "Mike Jiang", "partner": {"partner_age": +, "partner_name": "Galatea", "Partner_sex_is_male": false}, "Sex_is_male": true}*/}

The results of the compilation run are as follows:


The contents of the generated Demo.json file are as follows:



This tutorial sample code download Please click this link: Http://download.csdn.net/detail/tennysonsky


Resources:

Http://www.cnblogs.com/ggjucheng

http://my.oschina.net/Tsybius2014

Copyright NOTICE: This blog post, mostly I compiled, or in the network collection, reproduced please indicate the source!!

C + + reads and writes JSON files through the Jsoncpp class library

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.