(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 }

 測試結果:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章