(json-c学习2) linux c语言封装json数组(纯代码)

 头文件什么的都在上篇(json-c学习1) linux c语言解析json数组(纯代码),这里只写一个简单的函数:

209
210 int main(void)
211 {
212     char *body = TestBodyFunction();
213     ParsingBodyFunction(body);
214     printf("=====================================================\n");
215     //struct json_object *array = TestArrayFunction();
216     char *array = TestArrayFunction();
217     ParsingArrayFunction(array);
218     printf("=====================================================\n");
219     char *str = "[{\"loop_number\":1, \"sensor_address\":2}]";
220     int len = strlen(str);
221     printf("len = %d\n", len);
222     PkgArrayFunction();
223     return 0;
224 }
225
226

具体函数实现: 

170 void PkgArrayFunction(void)
171 {
172     //封装成如下形式的json内容:
173     /*
174     [
175         {"loop_number": 1,  "sensor_address":1},
176         {"loop_number": 1,  "sensor_address":1},
177         {"loop_number": 2,  "sensor_address":1},
178         {"loop_number": 2,  "sensor_address":1},
179         …
180     ]
181     */
182
183     SinglePointIdStruct array[10];
184     int i = 0;
185     for (i = 0; i < 10; i++)
186     {
187         array[i].loopNumber = i+5;
188         array[i].sensorAddress = i+10;
189     }
190     char *head = (char *)malloc(40*10*sizeof(char));
191     json_object *pValue = NULL;
192     json_object *pObjectSerPro = NULL;
193     json_object *jarray = json_object_new_array();  //建数组
194
195     for (i = 0; i < 10; i++)
196     {
197         json_object *pObj = json_object_new_object();
198         pValue = json_object_new_int(array[i].loopNumber);
199         json_object_object_add(pObj, LOOP_NUMBER, pValue);
200         pValue = json_object_new_int(array[i].sensorAddress);
201         json_object_object_add(pObj, SENSOR_ADDRESS, pValue);
202
203         json_object_array_add(jarray, pObj);  //将对象加入数组
204     }
205     memset(head, 0, 40*10*sizeof(char));
206     sprintf(head, "%s", (char*)json_object_to_json_string(jarray));
207     printf("head = %s\n", head);
208 }

 测试结果:

 

 

你可能感兴趣的:(json-c学习之路)