mosquitto_publish中的 JSON 字符串用法



Using C client library (libmosquitto)

如何将此 json 字符串发布到 MQTT mosquitto 代理

"book":[
    {"Name":"xyz", "price":"5.00"},
    {"Name":"abc", "price":"10.00"},
    {"Name":"hello world", "price":"15.00"}
]}
using this function.
    mosquitto_publish(mosq, NULL, "xyz", 10, "5.00", 2, false);
int mosquitto_publish(  mosq, mid, topic, payloadlen, payload, qos, retain);

回复晚了,但你会这样做:

 #include <json-c/json.h>
 json_object *jobjr = json_object_new_object();
 json_object *jattr = json_object_new_object();
 json_object *jid = json_object_new_string(id);
 json_object_object_add(jattr, "id", jid);
 json_object_object_add(jobjr, "report", jattr);
 const char *report = json_object_to_json_string(jobjr);
 mosquitto_publish(mosq, 0, options.status_topic, strlen(report), report, 1, false);
 json_object_put(jobjr);

关键是使用 json_object_to_json_string 将 JSON 对象转换为字符串。当然,如果你使用的是libjson。

最新更新