batuman
batuman

Reputation: 7304

How to implement cJSON_AddObjectToObject?

cJSON was used to create a json object is c. The following program was used to test. Tried to add a json object to another json object.

int main() { 
   cJSON *data = cJSON_CreateObject(); 
   cJSON_AddStringToObject(data, "target_list", "hce"); 
   cJSON_AddStringToObject(data, "source", "vas"); 
   cJSON_AddNumberToObject(data, "command_type", 2); 
   cJSON *camera1 = cJSON_CreateObject(); 
   cJSON_AddNumberToObject(camera1, "cam_id", 1); 
   cJSON_AddStringToObject(camera1, "url", "rtsp://ip:port/xxxxx");
   cJSON_AddNumberToObject(camera1, "enable_disable_flag", 1);
   cJSON_AddObjectToObject(data, "camera1"); 
  
   // convert the cJSON object to a JSON string 
   char *json_str = cJSON_Print(data); 
  
   printf("%s\n", json_str); 
   // free the JSON string and cJSON object 
   cJSON_free(json_str); 
   cJSON_Delete(json); 
   return 0; 
}

The output is

{
    "target_list":  "hce",
    "source":   "vas",
    "command_type": 2,
    "camera1":  {
    }
}

No content of camera1 is found in data.

Upvotes: -1

Views: 382

Answers (1)

batuman
batuman

Reputation: 7304

This is solution for me.

    cJSON *cam_list = cJSON_CreateArray();
    cJSON *camera1 = cJSON_CreateObject();
    cJSON_AddNumberToObject(camera1, "cam_id", 1); 
    cJSON_AddStringToObject(camera1, "url", "rtsp://ip:port/xxxxx"); 
    cJSON_AddNumberToObject(camera1, "enable_disable_flag", 1); 
    cJSON *camera2 = cJSON_CreateObject();
    cJSON_AddNumberToObject(camera2, "cam_id", 2); 
    cJSON_AddStringToObject(camera2, "url", "rtsp://ip:port/xxxxx"); 
    cJSON_AddNumberToObject(camera2, "enable_disable_flag", 1);
    cJSON_AddItemToArray(cam_list, camera1);
    cJSON_AddItemToArray(cam_list, camera2);
    cJSON *data = cJSON_CreateObject(); 
    cJSON_AddItemToObject(data, "cam_list", cam_list);
    cJSON *whole = cJSON_CreateObject(); 
    cJSON_AddStringToObject(whole, "target_list", "hce"); 
    cJSON_AddStringToObject(whole, "source", "vas"); 
    cJSON_AddNumberToObject(whole, "command_type", 2); 
    cJSON_AddItemToObject(whole, "data", data);
    char *json_str = cJSON_Print(whole);   

Upvotes: 0

Related Questions