C++ 遍历 JsonCpp 中的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4800605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:32:54  来源:igfitidea点击:

Iterating through objects in JsonCpp

c++jsonjsoncpp

提问by Steven smethurst

I have a C++ application that uses jsoncppto decode a JSON string. I have created the following function but it only shows me the top level objects...

我有一个 C++ 应用程序,它使用jsoncpp来解码 JSON 字符串。我创建了以下函数,但它只显示了顶级对象...

How do I get it to dump the entire object list?

我如何让它转储整个对象列表?

--Function--

- 功能 -

SaveJSON( json_data ); 

bool CDriverConfigurator::PrintJSONTree( Json::Value & root, unsigned short depth /* = 0 */) 
{
    printf( " {type=[%d], size=%d} ", root.type(), root.size() ); 

    if( root.size() > 0 ) {
        for( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {
            PrintJSONTree( itr.key(), depth+1 ); 
        }
        return true;
    }

    // Print depth. 
    for( int tab = 0 ; tab < depth; tab++) {
        printf( "-"); 
    }

    if( root.isString() ) {
        printf( " %s", root.asString().c_str() ); 
    } else if( root.isBool() ) {
        printf( " %d", root.asBool() ); 
    } else if( root.isInt() ) {
        printf( " %d", root.asInt() ); 
    } else if( root.isUInt() ) {
        printf( " %d", root.asUInt() ); 
    } else if( root.isDouble() ) {
        printf( " %f", root.asDouble() ); 
    }
    else 
    {
        printf( " unknown type=[%d]", root.type() ); 
    }


    printf( "\n" ); 
    return true;
}

--- Input ----

- - 输入 - -

{
   "modules":[
      {
         "config":{
            "position":[
               129,
               235
            ]
         },
         "name":"Modbus Task",
         "value":{
            "DeviceID":"This is the name",
            "Function":"01_READ_COIL_STATUS",
            "Length":"99",
            "Scan":"111",
            "Type":"Serve"
         }
      },
      {
         "config":{
            "position":[
               13,
               17
            ]
         },
         "name":"Modbus Connection",
         "value":{
            "Baud":"9600",
            "timeout":"2.5"
         }
      },
      {
         "config":{
            "position":[
               47,
               145
            ]
         },
         "name":"Modbus Device",
         "value":{
            "DeviceID":"55"
         }
      },
      {
         "config":{
            "position":[
               363,
               512
            ]
         },
         "name":"Function Something",
         "value":{

         }
      },
      {
         "config":{
            "position":[
               404,
               701
            ]
         },
         "name":"Function Something",
         "value":{

         }
      }
   ],
   "properties":{
      "Blarrg":"",
      "description":"",
      "name":"Modbus"
   },
   "wires":[
      {
         "src":{
            "moduleId":1,
            "terminal":"modbus.connection.output"
         },
         "tgt":{
            "moduleId":2,
            "terminal":"modbus.connection.input"
         }
      },
      {
         "src":{
            "moduleId":2,
            "terminal":"modbus.device.output"
         },
         "tgt":{
            "moduleId":0,
            "terminal":"modbus.device.output"
         }
      },
      {
         "src":{
            "moduleId":3,
            "terminal":"dataOut"
         },
         "tgt":{
            "moduleId":4,
            "terminal":"dataIn"
         }
      },
      {
         "src":{
            "moduleId":3,
            "terminal":"dataIn"
         },
         "tgt":{
            "moduleId":0,
            "terminal":"data1"
         }
      }
   ]
}

--Output--

- 输出 -

{type=[7], size=3} {type=[4], size=0} - modules
{type=[4], size=0} - properties
{type=[4], size=0} - wires 

回答by Omnifarious

You have some errors related to seemingly not having a great handle on recursion or the key->value nature of JSON and how that relates to the library you're using. I haven't tested this code at all, but it should work better.

您有一些与似乎没有很好地处理递归或 JSON 的键 > 值性质以及它与您使用的库的关系相关的错误。我根本没有测试过这段代码,但它应该工作得更好。

void CDriverConfigurator::PrintJSONValue( const Json::Value &val )
{
    if( val.isString() ) {
        printf( "string(%s)", val.asString().c_str() ); 
    } else if( val.isBool() ) {
        printf( "bool(%d)", val.asBool() ); 
    } else if( val.isInt() ) {
        printf( "int(%d)", val.asInt() ); 
    } else if( val.isUInt() ) {
        printf( "uint(%u)", val.asUInt() ); 
    } else if( val.isDouble() ) {
        printf( "double(%f)", val.asDouble() ); 
    }
    else 
    {
        printf( "unknown type=[%d]", val.type() ); 
    }
}

bool CDriverConfigurator::PrintJSONTree( const Json::Value &root, unsigned short depth /* = 0 */) 
{
    depth += 1;
    printf( " {type=[%d], size=%d}", root.type(), root.size() ); 

    if( root.size() > 0 ) {
        printf("\n");
        for( Json::Value::const_iterator itr = root.begin() ; itr != root.end() ; itr++ ) {
            // Print depth. 
            for( int tab = 0 ; tab < depth; tab++) {
               printf("-"); 
            }
            printf(" subvalue(");
            PrintJSONValue(itr.key());
            printf(") -");
            PrintJSONTree( *itr, depth); 
        }
        return true;
    } else {
        printf(" ");
        PrintJSONValue(root);
        printf( "\n" ); 
    }
    return true;
}

回答by JaredC

If you are just looking to print out the Json::Value, there's a methodfor that:

如果您只是想打印出 Json::Value,则有一种方法

Json::Value val;
/*...build the value...*/
cout << val.toStyledString() << endl;

Also, you may want to look into the Json::StyledWriter, the documentation for it is here. I believe it print a human friendly version. Also, Json::FastWriter, documentation here, prints a more compact form.

此外,您可能想查看Json::StyledWriter它的文档在这里。我相信它会打印一个人性化的版本。此外,此处的Json::FastWriter文档打印出更紧凑的表格。

回答by BattleTested

This is a good example that can print either jsonobjects and object member (and it's value) :

这是一个很好的例子,可以打印json对象和对象成员(及其值):

Json::Value root;               // Json root
Json::Reader parser;            // Json parser

// Json content
string strCarPrices ="{ \"Car Prices\": [{\"Aventador\":\"3,695\", \"BMW\":\",250\",\"Porsche\":\",000\",\"Koenigsegg Agera\":\".1 Million\"}]}";

// Parse the json
bool bIsParsed = parser.parse( strCarPrices, root );
if (bIsParsed == true)
{
    // Get the values
    const Json::Value values = root["Car Prices"];

    // Print the objects
    for ( int i = 0; i < values.size(); i++ )
    {
        // Print the values
        cout << values[i] << endl;

        // Print the member names and values individually of an object
        for(int j = 0; j < values[i].getMemberNames().size(); j++)
        {
            // Member name and value
            cout << values[i].getMemberNames()[j] << ": " << values[i][values[i].getMemberNames()[j]].asString() << endl;
        }
    }
}
else
{
    cout << "Cannot parse the json content!" << endl;
}

The output :

输出 :

{
        "Aventador" : "3,695",
        "BMW" : ",250",
        "Koenigsegg Agera" : ".1 Million",
        "Porsche" : ",000"
}
Aventador: 3,695
BMW: ,250
Koenigsegg Agera: .1 Million
Porsche: ,000

回答by Sergey Merkelov

There is an easy way to iterate over all fields in json::value. I omitted the printf stuff.

有一种简单的方法可以遍历 json::value 中的所有字段。我省略了 printf 的东西。

#include "cpprest/json.h"
#include "cpprest/filestream.h"

using web::json::value;
using std::wstring;

static void printOneValue(const wstring &key, const double &value);
static void printOneValue(const wstring &key, const bool &value);
static void printOneValue(const wstring &key, const int &value);
static void printOneValue(const wstring &key, const wstring &value);
static void printOne(const wstring &key, const value &v, _num level);
static void printTree(const value &v);

static void printTree(const value &v)
{
    if(!v.is_object())
        return;

    try
    {
        printOne(wstring(), v, 0);
    }
    catch(...)
    {
        // error handling
    }
}

static void printOne(const wstring &key, const value &v, _num level)
{
    switch(v.type())
    {
    case value::value_type::Number:
        if(v.is_double())
            printOneValue(key, v.as_double());
        else
            printOneValue(key, v.as_integer());
        break;
    case value::value_type::Boolean:
        printOneValue(key, v.as_bool());
        break;
    case value::value_type::String:
        printOneValue(key, v.as_string());
        break;
    case value::value_type::Object:
        for(auto iter : v.as_object())
        {
            const wstring &k = iter.first;
            const value &val = iter.second;
            printOne(k, val, level+1);
        }
        break;
    case value::value_type::Array:
        for(auto it : v.as_array())
        {
            printOne(key, it, level+1);
        }
        break;
    case value::value_type::Null:
    default:
        break;
    }
}

static void printOneValue(const wstring &key, const wstring &value)
{
    // process your key and value
}

static void printOneValue(const wstring &key, const int &value)
{
    // process your key and value
}

static void printOneValue(const wstring &key, const double &value)
{
    // process your key and value
}

static void printOneValue(const wstring &key, const bool &value)
{
    // process your key and value
}