|
| 1 | +Qx Declarative JSON {#declarativejson} |
| 2 | +====================================== |
| 3 | + |
| 4 | +FIXME |
| 5 | + |
| 6 | +Qx features a highly flexible, simple to use, declarative mechanism for parsing/serializing JSON data into user structs and other types. |
| 7 | + |
| 8 | +For example, the following JSON data: |
| 9 | + |
| 10 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.json} |
| 11 | +{ |
| 12 | + "title": "Sample JSON Data", |
| 13 | + "info": { |
| 14 | + "rating": 10, |
| 15 | + "cool": true |
| 16 | + }, |
| 17 | + "reviews": [ |
| 18 | + "Wicked!", |
| 19 | + "Awesome!", |
| 20 | + "Fantastic!" |
| 21 | + ] |
| 22 | +} |
| 23 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 24 | + |
| 25 | +can easily be parsed into a corresponding set of C++ data structures like so: |
| 26 | + |
| 27 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} |
| 28 | +#include <qx/core/qx-json.h> |
| 29 | +
|
| 30 | +struct Info |
| 31 | +{ |
| 32 | + int rating; |
| 33 | + bool cool; |
| 34 | +
|
| 35 | + QX_JSON_STRUCT(rating, cool); |
| 36 | +}; |
| 37 | +
|
| 38 | +struct MyJson |
| 39 | +{ |
| 40 | + QString title; |
| 41 | + Info info; |
| 42 | + QList<QString> reviews; |
| 43 | +
|
| 44 | + QX_JSON_STRUCT(title, info, reviews); |
| 45 | +}; |
| 46 | +
|
| 47 | +int main() |
| 48 | +{ |
| 49 | + QFile jsonFile("data.json"); |
| 50 | + MyJson myJsonDoc; |
| 51 | +
|
| 52 | + // Parse into custom structures |
| 53 | + Qx::JsonError je = Qx::parseJson(myJsonDoc, jsonFile); |
| 54 | + Q_ASSERT(!je.isValid()); |
| 55 | +
|
| 56 | + ... |
| 57 | +} |
| 58 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 59 | + |
| 60 | +Likewise, the structure can be serialized back out into textual JSON data with: |
| 61 | + |
| 62 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} |
| 63 | +int main() |
| 64 | +{ |
| 65 | + ... |
| 66 | +
|
| 67 | + // Serialize to JSON |
| 68 | + je = Qx::serializeJson(jsonFile, myJsonDoc); |
| 69 | + Q_ASSERT(!je.isValid()); |
| 70 | +} |
| 71 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 72 | + |
| 73 | +This system is accessed through the qx-json.h header, predominantly with QX_JSON_STRUCT(). |
0 commit comments