Lesen der JSON-Datei mit Boost

Lesen der JSON-Datei mit Boost


Ich habe eine Datei wie diese:


[data.json]


{
"electron": {
"pos": [0,0,0],
"vel": [0,0,0]
},
"proton": {
"pos": [1,0,0],
"vel": [0,0.1,0]
},
"proton": {
"pos": [-1,0,0],
"vel": [0,-0.1,-0.1]
}
}

Wie erstelle ich einen Partikelvektor aus der Analyse dieser Datei. So wie ich es verstehe, muss ich die Datei mit Boost lesen und die Zeichenfolgen (Zeilen) in einen Vektor lesen und dann den Inhalt des Vektors analysieren.


Das Klassenpartikel sieht in etwa so aus:


class Particle
{
private:
particle_type mtype; // particle_type is an enum
vector<double> mPos;
vector<double> mVel;
};

Andere Methoden für get/set wurden in der Klasse weggelassen.


Grundsätzlich hätte ich gerne Hilfe beim Erstellen eines vector<Particle> mit den korrekten Positions- und Geschwindigkeitsdaten und den darin analysierten Particle_type-Daten. Vielen Dank im Voraus.


Hauptcode:


int main(){
boost::property_tree::ptree pt;
boost::property_tree::read_json("data.json", pt);
}

Einige Code-Antworten


{
"name": "Aryan",
"class": "Masters in Maths with Comp Sc.",
"roll no": 3526, "address": {
"city": "Delhi",
"house no": "432-B",
"locality": "Omaxe City" } }
#include <iostream>
#include <string.h>
#include <exception>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include "json.hpp" using namespace std;
using json = nlohmann::json;
namespace pt = boost::property_tree;
int main() {
pt::ptree root;
pt::read_json("file.json", root); // Load the json file in this ptree int roll = root.get<int>("roll no"); //read and save the roll no in *roll* string name = root.get<string>("name"); //read and save the name in *name* string class1 = root.get<string>("class"); //read and save the class in *class1* cout <<
"name : " <<
name <<
endl; //getting the output of all cout <<
"roll no : " <<
roll <<
endl;
cout <<
"class : " <<
class1 <<
endl <<
"address : " <<
endl <<
endl;
for (pt::ptree::value_type &
v : root.get_child("address")) {
cout <<
v.first <<
endl;
cout <<
" "<<v.second.data() <<
endl;
} return 0;
}
Name :Aryan Rollennummer :3526 Klasse :Masters in Maths mit Comp Sc. Adresse:Stadt Delhi Haus Nr. 432-B Ort Omaxe City
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
using namespace std;
namespace pt = boost::property_tree;
int main() {
stringstream s;
s <<
"{ \"root\": { \"values\": [1, 2, 3, 4, 5 ] } }";
pt::ptree root; // Creates a root
pt::read_json(s, root); // Loads the json file in this ptree
for (pt::ptree::value_type&
v : root.get_child("root.values"))
{
cout <<
v.second.data() <<
endl; //gives the output
}
return 0;
1 2 3 4 5