首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在JsonCpp中迭代对象

在JsonCpp中迭代对象
EN

Stack Overflow用户
提问于 2011-01-26 01:18:33
回答 4查看 67K关注 0票数 31

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

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

--函数--

代码语言:javascript
运行
复制
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;
}

--输入--

代码语言:javascript
运行
复制
{
   "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"
         }
      }
   ]
}

--输出--

代码语言:javascript
运行
复制
{type=[7], size=3} {type=[4], size=0} - modules
{type=[4], size=0} - properties
{type=[4], size=0} - wires 
EN

回答 4

Stack Overflow用户

发布于 2011-01-26 02:06:16

如果您只是想打印出Json::Value,就会有一个方法

代码语言:javascript
运行
复制
Json::Value val;
/*...build the value...*/
cout << val.toStyledString() << endl;

另外,您可能需要查看Json::StyledWriter,它的文档是这里。我相信它会印出一个人类友好的版本。此外,Json::FastWriter,documentation 这里,打印一个更紧凑的表单。

票数 9
EN

Stack Overflow用户

发布于 2019-03-10 13:31:43

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

代码语言:javascript
运行
复制
Json::Value root;               // Json root
Json::Reader parser;            // Json parser

// Json content
string strCarPrices ="{ \"Car Prices\": [{\"Aventador\":\"$393,695\", \"BMW\":\"$40,250\",\"Porsche\":\"$59,000\",\"Koenigsegg Agera\":\"$2.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;
}

产出:

代码语言:javascript
运行
复制
{
        "Aventador" : "$393,695",
        "BMW" : "$40,250",
        "Koenigsegg Agera" : "$2.1 Million",
        "Porsche" : "$59,000"
}
Aventador: $393,695
BMW: $40,250
Koenigsegg Agera: $2.1 Million
Porsche: $59,000
票数 2
EN

Stack Overflow用户

发布于 2017-06-18 12:30:51

有一种简单的方法可以迭代json::value中的所有字段。我漏掉了打印出来的东西。

代码语言:javascript
运行
复制
#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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4800605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档