1

I found that the use of JsonCpp library parsed json string A, can not be resolved, the strange thing is that the analysis of string B is resolved successfully, when I take the string content when the program crashes, which is why? How can I avoid the crash?(string A:"http://192.168.1.1";string 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;
}
crazy
  • 11
  • 2

1 Answers1

0

What JSON do you expect the strings to contain?

Remember that JSON.parse accepts a string containing a valid JSON value. Neither of the strings you mention are valid JSON values ("192.168.1.1" and "http://192.168.1.1"), it could be that jsoncpp is accepting "192.168.1.1" as a number by ignoring the .1.1 part (if so this is a bug).

If you expect a string you should quote them twice (once for C++ and once for the JSON).

bool parsingSuccessful = reader.parse("\"http://192.168.1.1\"", root);

In this example the first (unescaped) double quotes (") tell C++ this is a string, then the escaped double quotes (\") lets jsoncpp to parse a string variable.

If your compiler supports raw string literals you can avoid escaping the quotes.

bool parsingSuccessful = reader.parse(R"("http://192.168.1.1")", root);

Another example:

bool parsingSuccessful = reader.parse(R("{"a": 42, "b": "hi"})", root);
Motti
  • 110,860
  • 49
  • 189
  • 262
  • I need to read the string from the config file, how can I ensure that the string is a valid JSON value. – crazy Nov 16 '17 at 02:16
  • @user7079007 wrap it in a `try` block and `catch` an exception if it's not valid. – Motti Nov 16 '17 at 10:12