柳鲲鹏
以前用json,因为方便都指定子串,所以没有用到库。这次还是使用公用库,也许内容复杂。
其实要讲解析,这个正是吾最擅长的。
产生json
int main(int argc, char* argv[]) { int count = 0; while (count < 10) { char message[128]; usleep(100*1000); count ++; struct json_object *json = json_object_new_object(); sprintf(message, "value %d", count); json_object_object_add(json, "text", json_object_new_string(message)); json_object_object_add(json, "int", json_object_new_int(count)); struct json_object *array = json_object_new_array(); sprintf(message, "array %d", count); json_object_array_add(array, json_object_new_string(message)); sprintf(message, "array %d", count*2); json_object_array_add(array, json_object_new_string(message)); json_object_object_add(json, "array", array); char *string = json_object_to_json_string(json); //mqtt_publish(LOCAL_IP, string); } return 0; }
解析json
/** 可以递归输出。 不过并无必要,需要什么获取什么。 */ static void mqtt_json_print(const char *sname, const json_object * pval) { enum json_type type; if (NULL == pval) { return; } /* json_type_null, json_type_boolean, json_type_double, json_type_int, json_type_object, json_type_string,*/ type = json_object_get_type(pval); switch(type) { case json_type_string: printf("Key:%s value: %s\n", sname, json_object_get_string(pval)); break; case json_type_int: printf("Key:%s value: %d\n", sname, json_object_get_int(pval)); break; case json_type_array: break; default: break; } return; } static void mqtt_json_get_print(json_object * jobj, const char *sname) { json_object *pval = json_object_object_get(jobj, sname); if (NULL != pval) { mqtt_json_print(sname, pval); } return; } static int mqtt_msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message) { char* payloadptr = (char*)message->payload; payloadptr[message->payloadlen] = 0; GH_LOG_INFO("topic=%s, msg=%s, size=%d", topicName, payloadptr, message->payloadlen); json_object *parsed_object= json_tokener_parse(payloadptr); //json_object_object_get_ex(parsed_object, "text", &value); mqtt_json_get_print(parsed_object, "text"); json_object_object_foreach(parsed_object, key, value) { mqtt_json_print(key, value); } MQTTClient_freeMessage(&message); MQTTClient_free(topicName); return MQTT_MSG_PROCESSED; }