【问题标题】:Writing a large array in one line using jsoncpp's StyledWriter使用 jsoncpp 的 StyledWriter 在一行中写入一个大数组
【发布时间】:2012-07-03 10:59:57
【问题描述】:

我使用jsoncpp来读写json文件。

对于写作,我使用 StyledWriter,它以人类可读的方式编写 json。

目前,我正在尝试将整数数组写入 json 文件。文档描述了写入数组值的以下规则:

  • 如果为空则打印 [] 不带缩进和换行
  • 如果数组不包含对象值、空数组或其他一些值类型,并且所有值都适合一行,则将数组打印在一行上。
  • 否则,如果值不适合一行,或者数组包含对象或非空数组,则每行打印一个值。

由于我要写入的数组对于一行来说太大了,根据上面的规则,作者每行打印一个值,这使得我的 json 变得丑陋且可读性降低。我更喜欢将整个数组写在一行或多行中,每行有几个值。

我知道 jasoncpp 是开源的,因此我可以改变作者来做我想做的事, 但我想知道是否有其他方法可以做到这一点。也许同时使用 FastWriter(创建单行 json)和 StyledWriter?

【问题讨论】:

标签: c++ json jsoncpp


【解决方案1】:

您应该按如下方式使用 FastWriter:

Json::Value your_json(Json::objectValue);
//init your json...
Json::FastWriter fastWriter;
fastWriter.write(your_json)

【讨论】:

    【解决方案2】:

    查看 json_writer.cpp - 两个 writeIndent() 方法。

    void 
    StyledStreamWriter::writeIndent()
    {
      /*
        Some comments in this method would have been nice. ;-)
    
       if ( !document_.empty() )
       {
          char last = document_[document_.length()-1];
          if ( last == ' ' )     // already indented
             return;
          if ( last != '\n' )    // Comments may add new-line
             *document_ << '\n';
       }
      */
    //Removing indent and line feed!!!   *document_ << '\n' << indentString_;
    }
    
    void 
    StyledWriter::writeIndent()
    {
       if ( !document_.empty() )
       {
          char last = document_[document_.length()-1];
          if ( last == ' ' )     // already indented
             return;
    //Removing indent and line feed!!!      if ( last != '\n' )    // Comments may add new-line
    //Removing indent and line feed!!!         document_ += '\n';
       }
       document_ += indentString_;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 2013-08-03
      相关资源
      最近更新 更多