JSON (JavaScript object Notation, JS tag) is a lightweight data interchange format. Typically used for data exchange or storage.
Jsoncpp is a C + + language-based open source Library for C + + program JSON data read and write operations.
Jsoncpp is an open source library
: Https://github.com/open-source-parsers/jsoncpp
Document Address: http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html
Use
An official integration solution: https://github.com/open-source-parsers/jsoncpp/wiki/Amalgamated
The simplest way to do this is to execute the project root directory in thepython脚本,构建头文件和源文件。
1. Enter the Jsoncpp project root directory in the console where the Python environment is installed,
2. Execute the command:
Python amalgamate.py
3. Copy the generated dist
directory
to your project, where the package source jsoncpp.cpp
and header filesjson.h、json-forwards.h
。
Basic classes and methods
jsoncpp
need to include header files when using libraries#include <json/json.h>(包含目录根据需要修改)
Method namespaces: Json
Common classes
Value: Used to store JSON data
Charreader: Abstract class for reading JSON data from a string
Implementation of the Charreaderbuilder:charreader class to read data from the standard input stream
Demo
Defines a JSON data structure and outputs it
Json::value Jsonroot;//defining the root nodeJson::value Jsonitem;//define a child objectjsonitem["item1"] =" One";//Add Datajsonitem["item2"] =2;jsonroot.append (jsonitem);Jsonitem.clear ();//Clear Jsonitem
jsonitem["item1.0"] = 1.0; jsonitem["item2.0"] = 2.0; Jsonroot["Item"] =Jsonitem;cout<< jsonroot.tostyledstring () << Endl;//Output to console
Writing JSON to a file
// standard output stream Ofs.open ("sample.json"// Create file // output Ofs.close ();
Reading JSON data from a file
ifstream IFS;//Standard input stream Ifs.open ("sample. JSON");
Jsonroot.clear ();
Json::charreaderbuilder builder;builder["collectcomments"false ; jsoncpp_string errs; if (!parsefromstream (Builder, IFS, &jsonroot, &errs)//Read data from IFS to jsonroot{ return ;}
Reading JSON data from a string
string jsonstr = jsonroot.tostyledstring ();//json string jsonroot.clear ();
Json::charreaderbuilder builder;builder["collectcomments"false; Jsoncpp_string errs; Json::charreader* reader = builder.newcharreader (); if (!reader->parse (Jsonstr.data (), Jsonstr.data () + jsonstr.size (), &jsonroot, &errs))// Read data from Jsonstr to jsonroot{ return;}
Gets the key-value pairs in the JSON
for 0; I < jsonroot.size (); i++) { for (auto sub= jsonroot[i].begin (); Sub! = Jsonroot[i].end (); sub++) { " " << jsonroot[i][sub.name ()] << Endl; }}
Using Jsoncpp to read and write JSON data in a C + + environment