JSON-CPP-如何从字符串初始化并获取字符串值? [英] Json-cpp - how to initialize from string and get string value?

查看:510
本文介绍了JSON-CPP-如何从字符串初始化并获取字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的代码崩溃(调试错误!已调用R6010 abort()).你能帮助我吗?我也想知道如何从字符串值初始化json对象.

My code below crashes(Debug Error! R6010 abort() has been called). Can you help me? I'd also would like to know how to initialize the json object from a string value.

Json::Value obj;
obj["test"] = 5;
obj["testsd"] = 655;
string c = obj.asString();

推荐答案

您好,这很简单:

1-您需要一个CPP JSON值对象(Json :: Value)来存储数据

1 - You need a CPP JSON value object (Json::Value) to store your data

2-使用Json Reader(Json :: Reader)读取JSON字符串并解析为JSON对象

2 - Use a Json Reader (Json::Reader) to read a JSON String and parse into a JSON Object

3-做你的事情:)

以下是执行这些步骤的简单代码:

Here is a simple code to make those steps:

#include <stdio.h>
#include <jsoncpp/json/json.h>
#include <jsoncpp/json/reader.h>
#include <jsoncpp/json/writer.h>
#include <jsoncpp/json/value.h>
#include <string>

int main( int argc, const char* argv[] )
{

    std::string strJson = "{\"mykey\" : \"myvalue\"}"; // need escape the quotes

    Json::Value root;   
    Json::Reader reader;
    bool parsingSuccessful = reader.parse( strJson.c_str(), root );     //parse process
    if ( !parsingSuccessful )
    {
        std::cout  << "Failed to parse"
               << reader.getFormattedErrorMessages();
        return 0;
    }
    std::cout << root.get("mykey", "A Default Value if not exists" ).asString() << std::endl;
    return 0;
}

要编译:g ++ YourMainFile.cpp -o main -l jsoncpp

To compile: g++ YourMainFile.cpp -o main -l jsoncpp

我希望它会有所帮助;)

I hope it helps ;)

这篇关于JSON-CPP-如何从字符串初始化并获取字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆