#include"include/json/json.h"
#include <iostream>
int main(int argc, char** argv)
{
//compile:g++ -o test json_value.cpp json_writer.cpp json_reader.cpp json_test.cpp -I./include
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
bool parsingSuccessful = reader.parse( "192.168.1.1", root );//http://192.168.1.1
if ( !parsingSuccessful )
{
// report to the user the failure and their locations in the document.
std::cout << "Failed to parse configuration\n"
<< reader.getFormattedErrorMessages();
return 0;
}
else
{
std::cout << "Successfully parse configuration" << endl;
}
// Get the value of the member of root named 'encoding', return 'UTF-8' if there is no
// such member.
std::string encoding = root.get("encoding", "UTF-8" ).asString();
// And you can write to a stream, using the StyledWriter automatically.
std::cout << "encoding:" <<encoding << endl;
return 0;
}
答案 0 :(得分:0)
您希望字符串包含哪些JSON?
请记住JSON.parse
接受包含有效JSON值的字符串。
您提到的字符串都不是有效的JSON值("192.168.1.1"
和"http://192.168.1.1"
),可能是jsoncpp通过忽略"192.168.1.1"
部分来接受.1.1
作为数字(如果所以这是一个错误。)
如果你期望一个字符串,你应该引用它们两次(一次用于C ++,一次用于JSON)。
bool parsingSuccessful = reader.parse("\"http://192.168.1.1\"", root);
在这个例子中,第一个(未转义的)双引号("
)告诉C ++这是一个字符串,然后转义的双引号(\"
)让jsoncpp解析一个字符串变量。
如果您的编译器支持raw string literals,则可以避免转义引号。
bool parsingSuccessful = reader.parse(R"("http://192.168.1.1")", root);
另一个例子:
bool parsingSuccessful = reader.parse(R("{"a": 42, "b": "hi"})", root);