简体   繁体   English

如何在C ++中使用Rapidjson获取嵌套的JSON值

[英]How to get nested JSON Values using Rapidjson in C++

In the below example, how to take the name and balance ? 在下面的例子中,如何namebalance

{
    "user": {
        "Name": "John",
        "Balance": "2000.53"
    }
}

Easy. 简单。

rapidjson::Document doc;
doc.Parse(str);
const Value& user = doc["user"];
string name = user["Name"].GetString();
string balance = user["Balance"].GetString();

I don't know Rapidjson much, only know it is a third-party library for parsing json in C++. 我不太了解Rapidjson,只知道它是用于在C ++中解析json的第三方库。 But I want to say, why don't you use boost for solve this problem. 但是我想说,为什么不使用boost来解决这个问题。 Give you my code, it has solved your problem perfectly. 给你我的代码,它完美地解决了你的问题。

Before run my code, please install boost library. 在运行我的代码之前,请安装boost库。 Strongly recommend it! 强烈推荐它!

#include <boost/property_tree/json_parser.hpp>

#include <string>

#include <sstream>

#include <iostream>

using namespace std;

int main()
{
    boost::property_tree::ptree parser;
    const string str = "{ \"user\": { \"Name\": \"John\", \"Balance\": \"2000.53\" } }";
    stringstream ss(str);
    boost::property_tree::json_parser::read_json(ss, parser);

    //get "user"
    boost::property_tree::ptree user_array = parser.get_child("user");

    //get "Name"
    const string name = user_array.get<string>("Name");
    //get "Balance"
    const string balance = user_array.get<string>("Balance");
    cout << name << ' ' << balance << endl;
    return 0;
}

The codes test well in gcc 4.7, boost 1.57. 代码在gcc 4.7中很好地测试,提升1.57。 You can get output: John 2000.53 . 你可以得到输出: John 2000.53 I think it can solve your problem. 我认为它可以解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM