I am using Modern C++ JSON to encode and decode JSON.
The examples and documentation while extensive do have a few holes particularly around extracting the data backout from the JSON data.
The following example shows how to encode a complex JSON object:
The examples and documentation while extensive do have a few holes particularly around extracting the data backout from the JSON data.
The following example shows how to encode a complex JSON object:
struct Point { double x_, y_, z_; }; nlohmann::json object = nlohmann::json::object(); { /// Create JSON object with data std::vector<Point> pnts_ = { { 0, 1, 2}, { 3, 4, 5} }; int id = 1; std::string desc( "description" ); int tid = -1; object["fp"]["id"] = id; object["fp"]["desc"] = desc; object["fp"]["tid"] = tid; nlohmann::json points = nlohmann::json::array(); for ( auto pnt : pnts_ ) { nlohmann::json point = nlohmann::json::object(); point["x"] = pnt.x_; point["y"] = pnt.y_; point["z"] = pnt.z_; points.push_back( point ); } object["points"] = points; object["size"] = pnts_.size(); }
The following shows how to decode the object created:{ /// Read JSON object const auto& itr = object.find( "fp" ); if ( itr == object.end() ) { /// error return false; } /// TODO do not assume the data is well formed. auto obj = itr.value(); auto idItr = obj.find( "id" ); int id = idItr->get<int>(); auto descItr = obj.find( "desc" ); std::string desc = descItr->get<std::string>(); auto trackItr = obj.find( "tid" ); int tid = trackItr->get<int>(); auto sizeItr = object.find( "size" ); int size( sizeItr->get<int>() ); auto pointsItr = object.find( "points" ); const auto& points = pointsItr.value(); std::vector<Point> pnts_; pnts_.reserve( size ); for ( auto pntItr : points.items() ) { const auto& pnt = pntItr.value(); Point point; point.x_ = pnt.find( "x" )->get<double>(); point.y_ = pnt.find( "y" )->get<double>(); point.z_ = pnt.find( "z" )->get<double>(); pnts_.push_back( point ); } }The following shows JSON object we created:{ "fp": {"desc":"description", "id":1, "tid":-1}, "points":[{"x":0.0,"y":1.0,"z":2.0},{"x":3.0,"y":4.0,"z":5.0}], "size":2 }
Comments
Post a Comment