JsonCpp : une nouvelle bibliothèque pour analyser le JSON en C++11
JsonCpp est une énième bibliothèque pour analyser le JSON en C++ sous licence MIT. Toutefois, malgré le côté déjà vu de celle-ci, vous pourriez être intéressé par JsonCpp pour :
- son utilisation du C++11 ;
- sa disponibilité en bibliothèque complètement implémentée dans les fichiers d'entêtes.
Autrement, celle-ci apporte les fonctionnalités habituelles permettant d'analyser les entrées au format JSON :
- lire et écrire des données au format JSON ;
- sérialisation/désérialisation ;
- attacher des commentaires C++ aux éléments durant l'analyse ;
- réécrire le document JSON en gardant les commentaires originaux.
Voici un exemple de code utilisant JsonCpp :
Vous pouvez retrouver le projet sur GitHub.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 Json::Value root; // 'root' will contain the root value after parsing. std::cin >> root; // You can also read into a particular sub-value. std::cin >> root["subtree"]; // Get the value of the member of root named 'encoding', // and return 'UTF-8' if there is no such member. std::string encoding = root.get("encoding", "UTF-8" ).asString(); // Get the value of the member of root named 'plug-ins'; return a 'null' value if // there is no such member. const Json::Value plugins = root["plug-ins"]; // Iterate over the sequence elements. for ( int index = 0; index < plugins.size(); ++index ) loadPlugIn( plugins[index].asString() ); // Try other datatypes. Some are auto-convertible to others. foo::setIndentLength( root["indent"].get("length", 3).asInt() ); foo::setIndentUseSpace( root["indent"].get("use_space", true).asBool() ); // Since Json::Value has an implicit constructor for all value types, it is not // necessary to explicitly construct the Json::Value object. root["encoding"] = foo::getCurrentEncoding(); root["indent"]["length"] = foo::getCurrentIndentLength(); root["indent"]["use_space"] = foo::getCurrentIndentUseSpace(); // If you like the defaults, you can insert directly into a stream. std::cout << root; // Of course, you can write to `std::ostringstream` if you prefer. // If desired, remember to add a linefeed and flush. std::cout << std::endl;
Pour rappel, voici un exemple de données au format JSON :
Code JSON : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9 { "encoding" : "UTF-8", "plug-ins" : [ "python", "c++", "ruby" ], "indent" : { "length" : 3, "use_space": true } }
Votre opinion
Quelle bibliothèque utilisez-vous pour analyser les entrées au format JSON ?
De quelles fonctionnalités avez-vous absolument besoin dans ce type de bibliothèques ?
Source
GitHub
Partager