2017-07-14 61 views
0

我試圖格式化一個json數組並將其發送到服務器。我已經嘗試了下面的代碼,並得到正確的字符串輸出。Json數組中的json對象的格式與for循環在C

json_t* json_arr = json_array(); 
json_t* json_request = json_object(); 
json_t* json_request1 = json_object(); 
json_t* host = json_object(); 
json_t* host1 = json_object(); 

char *buf; 
json_object_set_new(json_request, "mac", json_string("005056BD3B6C")); 
json_object_set_new(host, "os_type", json_string("Linux_Fedora")); 
json_object_set_new(host, "user_agent", json_string("Wget/1.10.2 (Fedora modified)")); 

json_object_set_new(json_request1, "mac", json_string("005056BD3B60")); 
json_object_set_new(host1, "os_type", json_string("Linux_Fedora")); 
json_object_set_new(host1, "user_agent", json_string("Wget/1.10.2 (Fedora modified)")); 

json_object_set_new(json_request ,"host", host); 
json_object_set_new(json_request1 ,"host", host1); 

json_array_append(json_arr ,json_request); 
json_array_append(json_arr ,json_request1); 
buf = json_dumps(json_arr ,JSON_PRESERVE_ORDER); 

輸出:

[ 
    { 
     "mac":"005056BD3B6C", 
     "host":{ 
     "os_type":"Linux_Fedora", 
     "user_agent":"Wget/1.10.2 (Fedora modified)" 
     } 
    }, 
    { 
     "mac":"005056BD3B60", 
     "host":{ 
     "os_type":"Linux_Fedora", 
     "user_agent":"Wget/1.10.2 (Fedora modified)" 
     } 
    } 
] 

我希望把中環上面的代碼按我requirement.so我嘗試下面的代碼。

json_t* json_arr = json_array(); 
char *buf; 
const char *str[3]; 
str[0] = "005056b4800c"; 
str[1] = "005056b4801c"; 
str[2] = "005056b4802c"; 

for (i=0;i<3;i++) 
{ 
    json_t* json_request = json_object(); 
    json_t* host = json_object(); 
    json_object_set_new(json_request, "mac", json_string(str[i])); 
    json_object_set_new(host, "os_type", json_string("Linux_Fedora")); 
    json_object_set_new(host, "user_agent", json_string("Wget/1.10.2 (Fedora modified)")); 
    json_object_set_new(json_request ,"host", host); 
    json_array_append(json_arr ,json_request); 
    json_decref(json_request); 
    json_decref(host); 
} 
buf = json_dumps(json_arr ,JSON_PRESERVE_ORDER); 

這裏我得到了下面的緩衝值:

[ 
    { 
     "mac":"005056b4800c", 
     "host":{ 
     "mac":"005056b4801c", 
     "host":{ 
      "mac":"005056b4802c", 
      "host":{ 

      } 
     } 
     } 
    }, 
    { 
     "mac":"005056b4801c", 
     "host":{ 
     "mac":"005056b4802c", 
     "host":{ 

     } 
     } 
    }, 
    { 
     "mac":"005056b4802c", 
     "host":{ 

     } 
    } 
] 

如何使用環和如上述相同的格式化陣列?

+0

也許你想告訴我們你正在使用哪個JSON庫。是Jansson嗎? – Gerhardh

回答

0

由於看起來您正在使用Jansson庫,因此您應該查看引用計數。

json_object_set_new(json_request ,"host", host); 
json_array_append(json_arr ,json_request); 
json_decref(json_request); 
json_decref(host); 

json_object_set_new「竊取」添加對象的引用。這意味着host的引用計數器在添加到父對象時不會遞增。 如果手動遞減計數器,則該對象將被釋放。 這會導致一個空的/無效的對象。

Host將被釋放,如果外部json_request是免費的。

遞減json_request的計數器是可以的,因爲json_array_append遞增計數器。

+0

感謝您的輸入。我現在能夠以正確的格式發送它。 – Jagan