【问题标题】:Converting a Json::Value to std::string?将 Json::Value 转换为 std::string?
【发布时间】:2015-06-24 23:02:48
【问题描述】:

我正在使用JsonCpp 构建一个 JSON 对象。构建对象后,有没有办法可以将对象作为std::string 获取?

【问题讨论】:

    标签: c++ stdstring jsoncpp


    【解决方案1】:

    Json::Writer is deprecated. 请改用Json::StreamWriterJson::StreamWriterBuilder

    Json::writeString 写入一个字符串流,然后返回一个字符串:

    Json::Value json = ...;
    Json::StreamWriterBuilder builder;
    builder["indentation"] = ""; // If you want whitespace-less output
    const std::string output = Json::writeString(builder, json);
    

    感谢 cdunn2001 的回答:How to get JsonCPP values as strings?

    【讨论】:

      【解决方案2】:

      这个小帮手可能会做。

      //////////////////////////////////////////////////
      // json.asString()
      //
      std::string JsonAsString(const Json::Value &json)
      {
          std::string result;
          Json::StreamWriterBuilder wbuilder;
      
          wbuilder["indentation"] = "";       // Optional
          result = Json::writeString(wbuilder, json);
          return result;
      }
      

      【讨论】:

        【解决方案3】:

        也可以使用 toStyledString() 方法。

        jsonValue.toStyledString();
        

        方法“toStyledString()”将任何值转换为格式化字符串。 另见链接:doc for toStyledString

        【讨论】:

          【解决方案4】:

          在我的上下文中,我在 json 值对象的末尾使用了一个简单的 .asString()。正如@Searene 所说,如果您想在之后处理它,它会消除您不需要的额外引号。

          Json::Value credentials;
          Json::Reader reader;
          
          // Catch the error if wanted for the reader if wanted. 
          reader.parse(request.body(), credentials);
          
          std::string usager, password;
          usager = credentials["usager"].asString();
          password = credentials["password"].asString();
          

          如果值是 int 而不是字符串,.asInt() 也很有效。

          【讨论】:

            【解决方案5】:

            如果您的Json::value 是字符串类型,例如以下json中的“bar”

            {
                "foo": "bar"
            }
            

            您可以使用Json::Value.asString 来获取bar 的值,而无需额外的引号(如果您使用StringWriterBuilder,则会添加)。这是一个例子:

            Json::Value rootJsonValue;
            rootJsonValue["foo"] = "bar";
            std::string s = rootJsonValue["foo"].asString();
            std::cout << s << std::endl; // bar
            

            【讨论】:

              【解决方案6】:

              您可以使用Json::Writer 来做到这一点,因为我假设您想将它保存在某个地方,这样您就不需要人类可读的输出,您最好的选择是使用Json::FastWriter,然后您可以调用write 方法与您的 Json::Value 参数(即您的根)然后简单地返回一个 std::string 像这样:

              Json::FastWriter fastWriter;
              std::string output = fastWriter.write(root);
              

              【讨论】:

              • 虽然这很好用,但当前版本的 JsonCPP 说 Json::FastWriter 已被弃用,取而代之的是 Json::StreamWriterBuilder。但是写入字符串的功能已被删除,现在需要写入 std::stringstream。你能详细说明一下吗?
              猜你喜欢
              • 2016-01-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-03-28
              相关资源
              最近更新 更多