boost generates and parses json

Posted by mutedgirl on Mon, 27 Dec 2021 19:15:36 +0100

boost generates and parses json [to]

Catalog

generate

analysis

Traversal Read Properties

Delete Node

Modify Value

throw

Problems needing attention during boost json usage

  • property_tree can parse data in xml, json, ini, info, and so on, using property_tree parsing uses these formats similarly.
  • Parsing json is simple, with the namespace boost::property_tree
    • Read_ The JSON function parses file streams and strings into ptree.
    • write_json outputs ptree as a string or file stream. The rest are operations on ptree.
  • put and add differences in ptree:
    • Add is to add an element with a duplicate name. put also adds an element with duplicate names overridden by new values.
  • Put_in ptree Child and add_child differences:
    • Same as above. put_child and add_child is the addition of a child object.
  • To parse the Json, you need to include a header file:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/date_time.hpp>
#include <boost/foreach.hpp>

generate

boost::property_tree::ptree pt_allitem;

unsigned char ucAttahId = 1;
boost::property_tree::ptree pt_item, pt_subitem;
pt_item.put("attachid", ucAttahId);
pt_subitem.put("mileage", 100.89);
pt_item.put_child("attachcontent", pt_subitem);

pt_allitem.add_child("attach",pt_item);
pt_allitem.add_child("attach", pt_item);
pt_allitem.add_child("attach", pt_item);

std::stringstream ss;
boost::property_tree::write_json(ss, pt_allitem);
std::string strContent = ss.str();

analysis

std::string strResponse = ""//json string to parse
boost::property_tree::ptree pt;
std::stringstream sstream(strResponse);

boost::property_tree::json_parser::read_json(sstream, pt);

int nErrorCode = pt.get<int>("errorCode");

boost::property_tree::ptree pChild_Payload;
pChild_Payload = pt.get_child("payload");
nTotalPageCount = pChild_Payload.get<int>("totalPage");
nCurrentPage = pChild_Payload.get<int>("curPage");

boost::property_tree::ptree pChild_ModelList = pChild_Payload.get_child("modelList");
//Traversing data
BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pChild_ModelList)
{
 boost::property_tree::ptree p = v.second;
 boost::property_tree::ptree ptDevice = p.get_child("device");
}

Traversal Read Properties

ptree m_pt;
string strAttrNameļ¼›
BOOST_FOREACH(ptree::value_type &v1, m_pt.get_child(L"root"))
{
    if (v1.first == L"Item")
    {
          strAttrName=v1.second.get<string>(L"<xmlattr>.name");
    }
}

Delete Node

  • Delete is the same, delete the node after traversal.
ptree  persons = pt.get_child("root.persons");
for(auto it = persons.begin(); it != persons.end();) 
{
   if(it->second.get<string>("name") == "dad")
        it = persons.erase(it);
    else
        ++it;
}

Modify Value

  • Changing is also simple. Traverse through the nodes to change the value, assign it directly and write it back.
iter2->second.put_value(value);

throw

  • property_tree has two kinds of exceptions, one is the path error, the other is the value error is good judgment, the exception tells you which attribute is wrong, etc.
try
{    
    .......
}
catch (boost::property_tree::ptree_bad_path& e)
{
    m_error = e.what();
    return false;
}
catch (boost::property_tree::ptree_bad_data& e)
{
    m_error =e.what();
    return false;
}

Problems needing attention during boost json usage

  • boost json does not support the generation of empty arrays, that is, json arrays can be generated with either a name of "" or other string and cannot be without a name (name is a key-value pair of "name": name in value); however, an empty array json string can be parsed.
    • How to generate an empty array JSON string, a compromise method is to generate an array with a name through Mr. boost json. Then by intercepting the string before and after []
  • Converting an empty string field to a number throws an exception.
  • boost json thread insecurity and its solution
    • The reason is that the ptree underlying dependency boost::spirit used in boost json parser is thread insecure and causes the program to run out of core. Solution:
    • Add the following macro anywhere the header file is introduced
#define BOOST_SPIRIT_THREADSAFE
#include <boost/property_tree/ptree.hpp>
#include<boost/property_tree/json_parser.hpp>
  • put int, double save as string instead of int, double solution
  • Generate and parse Chinese questions.
    • When boost's json format generates a string with Chinese characters, Chinese random code appears.
      • Reason: When using boost's ptree to output json, Chinese will be converted to utf8 encoding of \uxxx. In json's standard, Chinese is converted to utf16 encoding of \uxxx.
    • Solution:
      • Method 1: Use wptree to solve this problem.
      • Method 2: Use ptree but need to modify boost\property_tree\detail\json_parser_write.hpp code. The following: