【问题标题】:Create empty json array with jsoncpp使用 jsoncpp 创建空的 json 数组
【发布时间】:2012-10-28 21:15:27
【问题描述】:

我有以下代码:

void MyClass::myMethod(Json::Value& jsonValue_ref)
{
    for (int i = 0; i <= m_stringList.size(); i++)
    {
        if (m_boolMarkerList[i])
        {
            jsonValue_ref.append(stringList[i]);
        }
    }
}

void MyClass::myOuterMethod()
{
    Json::Value jsonRoot;
    Json::Value jsonValue;
    
    myMethod(jsonValue);

    jsonRoot["somevalue"] = jsonValue;
    Json::StyledWriter writer;
    std::string out_string = writer.write(jsonRoot);
}
    

如果m_boolMarkerList 中的所有标记均为假,则out_string 为{ "somevalue" : null },但我希望它是一个空数组:{ "somevalue" : [ ] }

有人知道如何实现吗?

非常感谢!

【问题讨论】:

    标签: c++ json jsoncpp


    【解决方案1】:

    好的,我明白了。这有点烦人,但毕竟很容易。 使用 jsoncpp 创建一个空的 json 数组:

    Json::Value jsonArray;
    jsonArray.append(Json::Value::null);
    jsonArray.clear();
    jsonRootValue["emptyArray"] = jsonArray;
    

    通过 writer 的输出将是:

    { "emptyArray" = [] }         
    

    【讨论】:

      【解决方案2】:

      这里有两种方法可以做到:

      jsonRootValue["emptyArray"] = Json::Value(Json::arrayValue);
      // or 
      jsonRootValue["emptyArray"] = Json::arrayValue;
      

      【讨论】:

      • 为什么不只是jsonRootValue["emptyArray"] = Json::arrayValue;
      • 我想也许当我发布这个问题时——比你的评论早两年——那是不可能的。
      【解决方案3】:

      您可以通过将 Value 对象定义为“数组对象”来做到这一点(默认情况下,它会将其作为“对象”对象,这就是为什么您的成员在没有分配时变为“null”,而不是 [] )

      所以,换行:

       Json::Value jsonValue;
       myMethod(jsonValue);
      

      用这个:

      Json::Value jsonValue(Json::arrayValue);
      myMethod(jsonValue);
      

      瞧!请注意,您可以将“arrayValue”更改为您想要的任何类型(对象、字符串、数组、int 等)以创建该类型的对象。正如我之前所说,默认的是“对象”。

      【讨论】:

      • 谢谢你 Ahmet 但这与 user609441 已经用更多文字说明的完全相同。
      • 也想说明原因^_^
      猜你喜欢
      • 2013-09-24
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多