JSONCPP Не правильно читать файлы
Итак, я недавно установил JSONCPP и по какой-то причине он дает мне ошибки при попытке использовать этот код:
#include <json.h>
#include <iostream>
#include <fstream>
int main(){
bool alive = true;
while (alive){
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
std::string test = "testis.json";
bool parsingSuccessful = reader.parse( test, root, false );
if ( !parsingSuccessful )
{
// report to the user the failure and their locations in the document.
std::cout << reader.getFormatedErrorMessages()
<< "\n";
}
std::string encoding = root.get("encoding", "UTF-8" ).asString();
std::cout << encoding << "\n";
alive = false;
}
return 0;
}
И вот файл:
{
"encoding" : "lab"
}
В нем говорится, что в строке 1, столбце 1 есть синтаксическая ошибка и что должно быть значение, объект или массив. Кто-нибудь знает, как это исправить?
EDIT: изменен на текущий код, из пастебина
Ответы
Ответ 1
См. документацию Json::Reader::parse
. Для этой перегрузки строка должна быть фактическим документом, а не именем файла.
Вы можете использовать istream overload вместо ifstream
.
std::ifstream test("testis.json", std::ifstream::binary);
EDIT: Я получил его с помощью:
#include "json/json.h"
#include <iostream>
#include <fstream>
int main(){
bool alive = true;
while (alive){
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
std::ifstream test("testis.json", std::ifstream::binary);
bool parsingSuccessful = reader.parse( test, root, false );
if ( !parsingSuccessful )
{
// report to the user the failure and their locations in the document.
std::cout << reader.getFormatedErrorMessages()
<< "\n";
}
std::string encoding = root.get("encoding", "UTF-8" ).asString();
std::cout << encoding << "\n";
alive = false;
}
return 0;
}
Ответ 2
#include "json/json.h"
#include <iostream>
#include <fstream>
int main(){
Json::Value root; // will contain the root value after parsing.
std::ifstream stream("testis.json", std::ifstream::binary);
stream >> root;
std::string encoding = root.get("encoding", "UTF-8" ).asString();
std::cout << encoding << "\n";
return 0;
}
Или в более общем плане:
#include "json/json.h"
#include <iostream>
#include <fstream>
int main(){
Json::Value root; // will contain the root value after parsing.
Json::CharReaderBuilder builder;
std::ifstream test("testis.json", std::ifstream::binary);
std::string errs;
bool ok = Json::parseFromStream(builder, test, &root, &errs);
if ( !ok )
{
// report to the user the failure and their locations in the document.
std::cout << errs << "\n";
}
std::string encoding = root.get("encoding", "UTF-8" ).asString();
std::cout << encoding << "\n";
return 0;
}
http://open-source-parsers.github.io/jsoncpp-docs/doxygen/namespace_json.html
Ответ 3
json не может содержать символы новой строки. Вместо этого попробуйте:
{"encoding": "lab"}
Вам может потребоваться обеспечить сохранение файла без окончательной новой строки.
РЕДАКТИРОВАТЬ. Возможно, ваш синтаксический анализатор переносит новые строки, но некоторые из них этого не делают. Что-то попробовать, если другие ответы не работают.