使用jsoncpp创建空的json数组

Mar*_*ser 17 c++ json jsoncpp

我有以下代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

如果所有boolMarkers都为false,则out_string为{"somevalue":null},但我希望它是一个空数组:{"somevalue":[]}

有谁知道如何实现这一目标?

非常感谢你!

小智 33

你也可以这样做:

jsonRootValue["emptyArray"] = Json::Value(Json::arrayValue);
Run Code Online (Sandbox Code Playgroud)

  • 为什么不只是`jsonRootValue ["emptyArray"] = Json :: arrayValue`; (11认同)

Ahm*_*kin 6

您可以通过将Value对象定义为"Array对象"来执行此操作(默认情况下,它将其作为"对象"对象,这就是为什么您的成员在未进行任何分配时变为"null"而不是[])

所以,切换这一行:

 Json::Value jsonValue;
 myMethod(jsonValue);
Run Code Online (Sandbox Code Playgroud)

有了这个:

Json::Value jsonValue(Json::arrayValue);
myMethod(jsonValue);
Run Code Online (Sandbox Code Playgroud)

瞧!请注意,您可以将"arrayValue"更改为您想要的任何类型(对象,字符串,数组,整数等)以生成该类型的对象.正如我之前所说,默认的是"对象".

  • 我也想解释一下原因^_^ (2认同)

Mar*_*ser 5

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

Json::Value jsonArray;
jsonArray.append(Json::Value::null);
jsonArray.clear();
jsonRootValue["emptyArray"] = jsonArray;
Run Code Online (Sandbox Code Playgroud)

通过 writer 的输出将是:

{ "emptyArray" = [] }         
Run Code Online (Sandbox Code Playgroud)