我想要一个JSonArray作为输出。我希望在该数组中添加json字符串。我正在使用json-glib和C ++。我在谷歌上搜索了很多,但都是徒劳的。我想要这样的东西:
[{" id":" i_am_id","客户":" i_am_C" ," tag":[{" one":" value"," two":" value"}]} ,{},{}]
"标记"是写的字符串的jsonarray。我想要一个像这样的jsonarray,其中有像string,int,jsonarrays这样的字段。请帮帮我。
答案 0 :(得分:0)
我没有使用json-glib,
我无法测试这段代码,
我省略了部分以释放builder
s,
但我希望这会对你有所帮助:
// 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);
}