Страницы

Поиск по вопросам

понедельник, 1 апреля 2019 г.

Как работать с jsoncpp?

Хочу воспользоваться библиотекой jsoncpp. Скачал с github, поставил с помощью cmake, как указано в документации. Только вот не могу ничего скомпилировать. Пример из документации вылетает с ошибками компиляции:
#include
Json::Value root; // starts as "null"; will contain the root value after parsing std::cin >> root;
// Get the value of the member of root named 'my-encoding', return 'UTF-32' if there is no // such member. std::string my_encoding = root.get("my-encoding", "UTF-32" ).asString();
// Get the value of the member of root named 'my-plug-ins'; return a 'null' value if // there is no such member. const Json::Value my_plugins = root["my-plug-ins"]; for ( int index = 0; index < my_plugins.size(); ++index ) // Iterates over the sequence elements. yourib::loadPlugIn( my_plugins[index].asString() );
yourlib::setIndentLength( root["my-indent"].get("length", 3).asInt() ); yourlib::setIndentUseSpace( root["my-indent"].get("use_space", true).asBool() );
// ... // At application shutdown to make the new configuration document: // Since Json::Value has implicit constructor for all value types, it is not // necessary to explicitly construct the Json::Value object: root["encoding"] = yourlib::getCurrentEncoding(); root["indent"]["length"] = yourlib::getCurrentIndentLength(); root["indent"]["use_space"] = yourlib::getCurrentIndentUseSpace();
// Make a new JSON document with the new configuration. Preserve original comments. std::cout << root << "
";
Ошибки:
a.cpp:18:4: error: ‘yourib’ has not been declared yourib::loadPlugIn( my_plugins[index].asString() ); ^ a.cpp:20:1: error: ‘yourlib’ has not been declared yourlib::setIndentLength( root["my-indent"].get("length", 3).asInt() ); ^ a.cpp:21:1: error: ‘yourlib’ has not been declared yourlib::setIndentUseSpace( root["my-indent"].get("use_space", true).asBool() ); ^ a.cpp:27:20: error: ‘yourlib’ has not been declared root["encoding"] = yourlib::getCurrentEncoding(); ^ a.cpp:28:28: error: ‘yourlib’ has not been declared root["indent"]["length"] = yourlib::getCurrentIndentLength(); ^ a.cpp:29:31: error: ‘yourlib’ has not been declared root["indent"]["use_space"] = yourlib::getCurrentIndentUseSpace(); ^
Компилятор: MinGW
В сети не нашёл детального объяснения использования данной библиотеки. Прошу, поделитесь опытом: как скомпилировать данный пример?
UPDATE
Если всё запихнуть в метод и сделать некоторые замены, то количество ошибок вообще зашкаливает:
#include #include
int main(){ Json::Value root; std::cin >> root; std::string my_encoding = root.get("my-encoding", "UTF-32" ).asString();
const Json::Value my_plugins = root["my-plug-ins"]; root["encoding"] = "cp1251"; //std::cout << root << "
"; return 0; }
Часть ошибок:
/usr/include/c++/4.8/istream:222:7: note: no known conversion for argument 1 from ‘Json::Value’ to ‘long double&’ /usr/include/c++/4.8/istream:235:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(void*&) [with _CharT = char; _Traits = std::char_traits; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream] operator>>(void*& __p) ^ /usr/include/c++/4.8/istream:235:7: note: no known conversion for argument 1 from ‘Json::Value’ to ‘void*&’ /usr/include/c++/4.8/istream:259:7: note: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__streambuf_type*) [with _CharT = char; _Traits = std::char_traits; std::basic_istream<_CharT, _Traits>::__streambuf_type = std::basic_streambuf] operator>>(__streambuf_type* __sb); ^ /usr/include/c++/4.8/istream:259:7: note: no known conversion for argument 1 from ‘Json::Value’ to ‘std::basic_istream::__streambuf_type* {aka std::basic_streambuf*}’ /usr/include/c++/4.8/istream:779:5: note: template std::basic_istream& std::operator>>(std::basic_istream&, signed char*) operator>>(basic_istream& __in, signed char* __s) ^ /usr/include/c++/4.8/istream:779:5: note: template argument deduction/substitution failed: a.cpp:6:14: note: cannot convert ‘root’ (type ‘Json::Value’) to type ‘signed char*’ std::cin >> root; ^ In file included from /usr/include/c++/4.8/iostream:40:0, from a.cpp:2: /usr/include/c++/4.8/istream:774:5: note: template std::basic_istream& std::operator>>(std::basic_istream&, unsigned char*) operator>>(basic_istream& __in, unsigned char* __s) ^ /usr/include/c++/4.8/istream:774:5: note: template argument deduction/substitution failed: a.cpp:6:14: note: cannot convert ‘root’ (type ‘Json::Value’) to type ‘unsigned char*’ std::cin >> root; ^ In file included from /usr/include/c++/4.8/iostream:40:0, from a.cpp:2: /usr/include/c++/4.8/istream:732:5: note: template std::basic_istream& std::operator>>(std::basic_istream&, signed char&) operator>>(basic_istream& __in, signed char& __c) ^ /usr/include/c++/4.8/istream:732:5: note: template argument deduction/substitution failed: a.cpp:6:14: note: cannot convert ‘root’ (type ‘Json::Value’) to type ‘signed char&’ std::cin >> root; ^ In file included from /usr/include/c++/4.8/iostream:40:0, from a.cpp:2: /usr/include/c++/4.8/istream:727:5: note: template std::basic_istream& std::operator>>(std::basic_istream&, unsigned char&) operator>>(basic_istream& __in, unsigned char& __c) ^ /usr/include/c++/4.8/istream:727:5: note: template argument deduction/substitution failed: a.cpp:6:14: note: cannot convert ‘root’ (type ‘Json::Value’) to type ‘unsigned char&’ std::cin >> root; ^ In file included from /usr/include/c++/4.8/istream:882:0, from /usr/include/c++/4.8/iostream:40, from a.cpp:2: /usr/include/c++/4.8/bits/istream.tcc:923:5: note: template std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&, _CharT&) operator>>(basic_istream<_CharT, _Traits>& __in, _CharT& __c) ^ /usr/include/c++/4.8/bits/istream.tcc:923:5: note: template argument deduction/substitution failed: a.cpp:6:14: note: deduced conflicting types for parameter ‘_CharT’ (‘char’ and ‘Json::Value’) std::cin >> root; ^ In file included from /usr/include/c++/4.8/istream:882:0, from /usr/include/c++/4.8/iostream:40, from a.cpp:2: /usr/include/c++/4.8/bits/istream.tcc:955:5: note: template std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&, _CharT2*) operator>>(basic_istream<_CharT, _Traits>& __in, _CharT* __s) ^ /usr/include/c++/4.8/bits/istream.tcc:955:5: note: template argument deduction/substitution failed: a.cpp:6:14: note: mismatched types ‘_CharT2*’ and ‘Json::Value’ std::cin >> root; ^ In file included from /usr/include/c++/4.8/string:53:0, from /usr/include/json/value.h:12, from a.cpp:1: /usr/include/c++/4.8/bits/basic_string.tcc:996:5: note: template std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&, std::basic_string<_CharT, _Traits, _Alloc>&) operator>>(basic_istream<_CharT, _Traits>& __in, ^ /usr/include/c++/4.8/bits/basic_string.tcc:996:5: note: template argument deduction/substitution failed: a.cpp:6:14: note: ‘Json::Value’ is not derived from ‘std::basic_string<_CharT, _Traits, _Alloc>’ std::cin >> root;


Ответ

Наконец-то удалось заставить работать эту библиотеку. Я пользовался GCC версии 4.8.4 и Python 2.7.6. Нужно скачать библиотеку с официального GitHub репозитория и разархивировать куда-нибудь. Затем в в терминале перейти в получившуюся директорию и запустить:
python amalgamate.py
После того, как увидите сообщение Source succesfully amalagated в этой папке появится новая директория dist. Там есть файлы библиотеки, которые нам понадобятся. Содержимое папки dist можно свободно перемещать куда-угодно. Структура у неё следующая :
dist |-- json | |-- json-forwards.h | `-- json.h `-- jsoncpp.cpp
В качестве примера можно использовать этот код:
#include #include
int main(){
Json::Value root; // starts as "null"; will contain the root value after parsing
root["encoding"] = "UTF-8"; root["indent"]["length"] = "Some text"; root["indent"]["use_space"] = "Some user_space text";
std::cout << root << "
"; return 0; }
Сохраняем этот код в файл с названием a.cpp (можно любое другое) и кладём его рядом с файлом jsoncpp.cpp. А теперь из командной строки выполняем:
g++ a.cpp jsoncpp.cpp -std=c++11
При успешной компиляции никакого вывода в консоль тут быть не должно. После этого выполняем:
./a.out
и видим результат:
{ "encoding" : "UTF-8", "indent" : { "length" : "Some text", "use_space" : "Some user_space text" } }
Спасибо большое @VladD за помощь в этом запутанном деле.

Комментариев нет:

Отправить комментарий