boost parsing JSON-formatted text
Flyfish 2015-4-1
Property_tree can parse text in Ini,xml,json,info and other formats
The following example is parsing text in JSON format
header files that need to be included
#include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp>const std:: String file_path= "C:\\Test.txt";
Generate Data
void Generate_user () {boost::p Roperty_tree::p tree root; Boost::p roperty_tree::p tree items;boost::p roperty_tree:: Ptree item1;item1.put ("ID", "1"); Item1.put ("Name", "Wang"); Items.push_back (Std::make_pair ("1", item1)); Boost:: Property_tree::p tree item2;item2.put ("ID", "2"), Item2.put ("Name", "Zhang"), Items.push_back (Std::make_pair ("2", ITEM2); boost::p roperty_tree::p tree item3;item3.put ("ID", "3") Item3.put ("Name", "Li"); Items.push_back (Std::make_ Pair ("3", Item3)), Root.put_child ("user", items), boost::p Roperty_tree::write_json (file_path,root);}
Reading data
void Read_user () {boost::p roperty_tree::p tree root;boost::p roperty_tree::p tree items;boost::p roperty_tree::read_ Json<boost::p roperty_tree::p tree> (File_path,root); Items=root.get_child ("user"); for (boost::p roperty_tree: :p tree::iterator It=items.begin (); It!=items.end () ++it) {//Traverse read Data string Key=it->first;//key idstring ID=it-> Second.get<string> ("ID"); string name=it->second.get<string> ("Name");}}
The data in the file
{" user": {"1": {" id": "1", "name": "Wang"}, "2": {"id": "2", "Name": "Zhang"}, "3": {"id": "3", "name": "Li"}}}
Boost parsing JSON-formatted text