简体   繁体   中英

How to get nested JSON Values using Rapidjson in C++

In the below example, how to take the name and balance ?

{
    "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++. But I want to say, why don't you use boost for solve this problem. Give you my code, it has solved your problem perfectly.

Before run my code, please install boost library. 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. You can get output: John 2000.53 . I think it can solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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