1

使用 C 客户端库 (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);
4

1 回答 1

0

迟到的回复,但你会这样做:

 #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 对象转换为字符串json_object_to_json_string。那是如果你当然使用 libjson。

于 2016-10-20T10:22:08.357 回答