【问题标题】:Why JsonCpp library parsing string success, take the string when the program is crash?为什么JsonCpp库解析字符串成功,程序崩溃时取字符串?
【发布时间】:2017-07-20 04:02:51
【问题描述】:

发现使用JsonCpp库解析json字符串A,无法解析,奇怪的是解析字符串B解析成功,当我取字符串内容时程序崩溃,这是为什么?如何避免崩溃?(字符串 A:"http://192.168.1.1";字符串 B:"192.168.1.1";)

#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;
}

【问题讨论】:

    标签: jsoncpp


    【解决方案1】:

    您希望字符串包含什么 JSON?

    请记住,JSON.parse 接受包含有效 JSON 值的字符串。 您提到的两个字符串都不是有效的 JSON 值("192.168.1.1""http://192.168.1.1"),可能是 jsoncpp 通过忽略 .1.1 部分接受 "192.168.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);
    

    【讨论】:

    • 我需要从配置文件中读取字符串,如何确保字符串是有效的JSON值。
    猜你喜欢
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2014-06-15
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多