我想要一个JSonArray作为输出,我想要在该数组中添加json字符串。我为此使用json-glib和C ++。我该死的在Google上搜索了很多东西,但徒劳无功。我想要这样的东西:
[{“ id”:“ i_am_id”,“ client”:“ i_am_C”,“ tag”:[{“ one”:“ value”,“ two”:“ value”}]},{},{}]
“标签”是所写字符串的jsonarray。我想要像这样的许多json的jsonarray,其中有诸如string,int,jsonarrays之类的字段。请帮我解决一下这个。
最佳答案
我没有使用json-glib,
我无法测试此代码,
我省略了发布builder
的部分,
但我希望这对您有帮助:
// build an object as an element of 'tag' array.
// {"one": "value", "two": "value"}
JsonNode * objectAsElementOfTag;
{
JsonBuilder *builder = json_builder_new ();
json_builder_begin_object (builder);
json_builder_set_member_name (builder, "one");
json_builder_add_string_value (builder, "value");
json_builder_set_member_name (builder, "two");
json_builder_add_string_value (builder, "value");
json_builder_end_object (builder);
objectAsElementOfTag = json_builder_get_root (builder);
}
// build 'tag' array.
// [{"one": "value", "two": "value"}]
JsonNode * tagArray;
{
JsonBuilder *builder = json_builder_new ();
json_builder_begin_array (builder);
json_builder_add_value (builder, objectAsElementOfTag);
json_builder_end_array (builder);
tagArray = json_builder_get_root (builder);
}
// build the first element.
// {"id": "i_am_id", "client":"i_am_C" ,"tag": [{"one": "value", "two": "value"}] }
JsonNode * firstElement;
{
JsonBuilder *builder = json_builder_new ();
json_builder_begin_object (builder);
json_builder_set_member_name (builder, "id");
json_builder_add_string_value (builder, "i_am_id");
json_builder_set_member_name (builder, "client");
json_builder_add_string_value (builder, "i_am_C");
json_builder_set_member_name (builder, "tag");
json_builder_add_value (builder, tagArray);
json_builder_end_object (builder);
firstElement = json_builder_get_root (builder);
}
// build the second element(an empty object).
// {}
JsonNode * secondElement;
{
JsonBuilder *builder = json_builder_new ();
json_builder_begin_object (builder);
json_builder_end_object (builder);
secondElement = json_builder_get_root (builder);
}
// build the third element(an empty object).
// {}
JsonNode * thirdElement;
{
JsonBuilder *builder = json_builder_new ();
json_builder_begin_object (builder);
json_builder_end_object (builder);
thirdElement = json_builder_get_root (builder);
}
// finally, build the root array which may be what you want.
// [ {"id": "i_am_id", "client":"i_am_C" ,"tag": [{"one": "value", "two": "value"}] } ,{} ,{} ]
JsonNode * rootArray;
{
JsonBuilder *builder = json_builder_new ();
json_builder_begin_array (builder);
json_builder_add_value (builder, firstElement);
json_builder_add_value (builder, secondElement);
json_builder_add_value (builder, thirdElement);
json_builder_end_array (builder);
rootArray = json_builder_get_root (builder);
}
关于c++ - 如何在一个JsonArray中添加许多json字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26987891/