C++ 使用 jsoncpp 创建空的 json 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13293043/
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
Create empty json array with jsoncpp
提问by Martin Meeser
I have following code:
我有以下代码:
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);
}
If all boolMarkers are false the out_string is { "somevalue" : null } but I want it to be an empty array: { "somevalue" : [ ] }
如果所有 boolMarkers 都是假的 out_string 是 { "somevalue" : null } 但我希望它是一个空数组:{ "somevalue" : [ ] }
Does anybody know how to achieve this?
有谁知道如何实现这一目标?
Thank you very much!
非常感谢!
回答by Michal Sabo
You can do it also this way:
你也可以这样做:
jsonRootValue["emptyArray"] = Json::Value(Json::arrayValue);
回答by Ahmet Ipkin
You can do this by defining the Value object as an "Array object" (by default it makes it as an "object" object which is why your member becomes "null" when no assignment made, instead of [] )
您可以通过将 Value 对象定义为“数组对象”来做到这一点(默认情况下,它使其成为“对象”对象,这就是为什么您的成员在未进行赋值时变为“空”而不是 [] 的原因)
So, switch this line:
所以,切换这一行:
Json::Value jsonValue;
myMethod(jsonValue);
with this:
有了这个:
Json::Value jsonValue(Json::arrayValue);
myMethod(jsonValue);
And voila! Note that you can change "arrayValue" to any type you want (object, string, array, int etc.) to make an object of that type. As I said before, the default one is "object".
瞧!请注意,您可以将“arrayValue”更改为您想要的任何类型(对象、字符串、数组、整数等)以创建该类型的对象。正如我之前所说,默认的是“对象”。
回答by Martin Meeser
OK I got it. It is a little bit annoying but it is quite easy after all. To create an empty json array with jsoncpp:
好,我知道了。这有点烦人,但毕竟很容易。使用 jsoncpp 创建一个空的 json 数组:
Json::Value jsonArray;
jsonArray.append(Json::Value::null);
jsonArray.clear();
jsonRootValue["emptyArray"] = jsonArray;
Output via writer will be:
通过编写器的输出将是:
{ "emptyArray" = [] }