1,cJSON支持在C程序中创建和解析JSON数据,其提供多种方法供C程序使用,最直接的是将cJSON.c和cJSON.h加入到C工程中,源代码:https://github.com/DaveGamble/cJSON
2, QJsonObject用于在Qt中创建JSON对象
3,数据传输通过UDP运行
Qt代码如下:
首先在pro文件中加入
QT += network
h文件内容:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include<QtNetwork> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); QUdpSocket *sender; QByteArray byteArray; private slots: void on_pushButton_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
cpp文件内容:
#include "mainwindow.h" #include "ui_mainwindow.h" #include<QJsonObject> #include<QJsonDocument> #include<QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); sender = new QUdpSocket(this); QJsonObject rectJson; rectJson.insert("Type","Rectangle"); rectJson.insert("height",42); rectJson.insert("widght",23); QJsonDocument rectJsonDoc; rectJsonDoc.setObject(rectJson); byteArray = rectJsonDoc.toJson(QJsonDocument::Compact); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QHostAddress address; address.setAddress(QString("192.168.230.140")); sender->writeDatagram(byteArray.data(),byteArray.size(), address,4444); }
Qt程序通过端口4444,向IP为192.168.230.140的主机发送JSON数据
4,C程序如下:
{ int sock_fd; char rcv_buff[512]; struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_len; int rcv_num = -1; if ((sock_fd = socket(AF_INET, SOCK_DGRAM,0)) < 0) { perror("socket create error "); exit(1); } memset(&server_addr,0,sizeof(struct sockaddr_in)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(4444); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); client_len = sizeof(struct sockaddr_in); if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0) { perror("bind socket error. "); exit(1); } while (1) { /*zero the buff of rvbsm and hvbsm? zhp*/ rcv_num= recvfrom(sock_fd, rcv_buff, sizeof(rcv_buff), 0, (struct sockaddr*)&client_addr, &client_len); if (rcv_num>0) { rcv_buff[rcv_num] = '