There are cases where, in order to provide information to an external application, data needs to be output in XML format or JSON. A case in point would be the Ajax applications.
Send the Contents of the Model in JSON Format
Here is an example of sending a JSON object from the controller.
| Blog blog = Blog::get(10);
That's all. The model that is generated by the generator, is provided by the toVariantMap() method to convert QVariantMap object itself. It’s important to note that this method will convert all the properties a model has, therefore the method should be implemented separately for separate properties if there is information to be concealed.
Sending All Blog Objects in List Format
| renderJson( Blog::getAllJson() );
This also simple! However, please note that if there are a large number of records in the blog database results could be unexpected.
In addition to this, the following methods are available. Please check this, because there is little information on the API reference.
| bool renderJson(const QJsonDocument &document);
bool renderJson(const QJsonObject &object);
bool renderJson(const QJsonArray &array);
bool renderJson(const QVariantMap &map);
bool renderJson(const QVariantList &list);
bool renderJson(const QStringList &list);
Send the Contents of the Model in XML Format
The way to send the contents of the model in XML format is not much different from the way we send in JSON format. Call one of the following methods:
| bool renderXml(const QDomDocument &document);
bool renderXml(const QVariantMap &map);
bool renderXml(const QVariantList &list);
bool renderXml(const QStringList &list);
If the input from the output of these does not suit your requirements, you can implement a new template. How to implement is described in the view chapter, but do not forget that you only set the content type of the response in the controller.