How to Send and Receive JSON Requests in Qt

Posted on Posted in Qt Tutorials, Tutorials

There are many APIs on the web that accept JSON requests and reply using JSON. An example for this can be most of Google’s API services. For example if you are writing a Qt application that needs JSON interaction with a Google API (such as Google Webmaster API) you can easily send requests and receive responses if you follow these steps.

First of all make sure that your Qt project is using network module by adding the following line to your .pro file.

QT += network

Next you have to add QtNetwork header files to your source code using the line below.

#include <QtNetwork>

Now you need to create a request using the specific URL for that web service or API.

QNetworkRequest request(QUrl(“”));

You have to set the request header content type as seen below:

request.setHeader(QNetworkRequest::ContentTypeHeader, “application/json”);

Then you have to create your JSON request. (What is shown here is just an example and not a real JSON request.)

QJsonObject json;

body.insert(“item1”, “value1”);

body.insert(“item2”, “value2”);

Now you have to create a Network Access object which will help with sending the request.

QNetworkAccessManager nam;

And send (POST) your JSON request. Result will be saved in a QNetworkRply

QNetworkReply *reply =, QJsonDocument(json).toJson());

You have to wait for the response from server.





When server sends you the response, you have to store it like this:

QByteArray response_data = reply->readAll();

Assuming that the response is a JSON object you can change its format like this:

QJsonDocument json = QJsonDocument::fromJson(response_data);

One last thing to note is that you have to clean up the reply object by yourself using the line below:


Leave a Reply

Your email address will not be published. Required fields are marked *