C ++ JsonCpp:遍历对象并获取值

时间:2018-04-15 15:58:54

标签: c++ jsoncpp

我有点问题。 我的json看起来像这样:

{
"data" : 
{
    "Money" : 
    {
        "testUser3" : "500",
        "testUser2" : "23",
        "testUser1" : "2435",
        "testUser" : "60"
    }
}}

我正在尝试获取所有用户的值+名称..但我不知道如何,因为用户名可以更改我无法使用root["data"]["Money"]["testUser"].asInt(); 我希望有人可以帮助我,谢谢。

1 个答案:

答案 0 :(得分:0)

你被投票了,但无论如何我都会帮助你,因为我需要类似的东西..让我们在JsonCpp - when having a json::Value object, how can i know it's key name?中感谢Brandon的关键部分..

#include <string>
#include <iostream>

#include "jsoncpp-master/include/json/value.h"
#include "jsoncpp-master/include/json/json.h"

using namespace std;

bool Testjson2()
{
    string s =
        "   { \"data\" :{"
        "           \"Money\" : {"
        "               \"testUser3\" : \"500\","
        "               \"testUser2\" : \"23\","
        "               \"testUser1\" : \"2435\","
        "               \"testUser\"  : \"60\""
        "           }"
        "   } }";
    Json::Value root;
    Json::Reader reader;
    string sdress = "{\"\":[" + s + "]}";
    if (!reader.parse(sdress, root))
    {
        cout << sdress << "\n" << "Parse error\n";
        return false;
    }
    const Json::Value datasections = root[""];
    Json::Value  v = datasections [0]["data"]["Money"];
    cout << "There are " << v.size() << " members\n";
    for (auto const& id : v.getMemberNames()) 
        cout << id << " has " << v[id] << std::endl;
    return true;
}