2017-07-14 35 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