(json-c學習3) linux c語言封裝json單個對象(純代碼)

 頭文件什麼的都在首篇(json-c學習1) linux c語言解析json數組(純代碼),這裏只寫一個簡單的函數:

210 void PkgJsonFunction(void)
211 {
212     //封裝成如下形式的json內容:
213     /*
214         {
215                 "loop_number": 1,
216                 "sensor_address": 1
217         }
218     */
219     json_object *pValue = NULL;
220     json_object *pObjectSerPro = NULL;
221     char msg[48] = {0};
222     int loopNumber = 10;
223     int sensorAddress = 10;
224     //創建json對象
225     pObjectSerPro = json_object_new_object();
226     //添加內容
227     pValue = json_object_new_int(loopNumber);
228     json_object_object_add(pObjectSerPro, LOOP_NUMBER, pValue);
229     pValue = json_object_new_int(sensorAddress);
230     json_object_object_add(pObjectSerPro, SENSOR_ADDRESS, pValue);
231
232     memset(msg, 0, 48);
233     sprintf(msg, "%s", json_object_to_json_string(pObjectSerPro));
234
235     printf("msg = %s\n", msg);
236 }
237 int main(void)
238 {
239     char *body = TestBodyFunction();
240     ParsingBodyFunction(body);
241     printf("=====================================================\n");
242     //struct json_object *array = TestArrayFunction();
243     char *array = TestArrayFunction();
244     ParsingArrayFunction(array);
245     printf("=====================================================\n");
246     char *str = "[{\"loop_number\":1, \"sensor_address\":2}]";
247     int len = strlen(str);
248     printf("len = %d\n", len);
249     PkgArrayFunction();
250     printf("=====================================================\n");
251     PkgJsonFunction();
252
253     return 0;
254 }
255
256

測試結果:

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