JSON this child familiar and unfamiliar, today to the students talk about how QT is using JSON, a word: simple
1. What is JSON?
A:json is a <key,value> string
① a JSON object
{"Name": "Xupeidong", "Age": "18"}
② nested JSON objects inside a JSON array
[{"Price": "1", "Name": "1", "id": "1"}, {"Price": "2", "Name": "2", "id": "2"}, {"Price": "3", "Name": "3", "id": "3"}]
2. How to use JSON inside QT
#include <QJsonDocument> //parsing class for converting JSON to Qbytearrar, or parsing from Qbytearray json#include <QJsonArray> //Encapsulate JSON array: ["1", "2", "3"] #include <QJsonObject> //Encapsulate JSON object: {"name": "111", "Pass": 222} #include < Qjsonparseerror>//Error class
①json Object
Assembly:
Qjsonobject Json;json.insert ("name", "111"); Json.insert ("Pass", 222); Qjsondocument Doc;doc.setobject (JSON); Qbytearray byte = Document.tojson (Qjsondocument::compact);
Analytical:
Qjsonparseerror error; Qjsondocument doc = Qjsondocument::fromjson (byte, &error); if (Error.error = = qjsonparseerror::noerror) { if (Doc.isobject ()) { Qjsonobject obj = Doc.object (); if (Obj.contains ("name")) {Qjsonvalue value = Obj.take ("name"); Qdebug () << value.tostring (); }}}
②json Array
Assembly:
Format: "[\" 000\ ", \" 111\ "]" Qjsonarray json;json.insert (0, "); Json.insert (1," 111 "); Qjsondocument Doc;doc.setarray (JSON); Qbytearray byte = Doc.tojson (Qjsondocument::compact);
You can also insert a JSON object: Format: "[{\" 0\ ": \" 000\ "},{\" 1\ ": \" 111\ "}]" Qjsonarray json; Qjsonobject Obj;obj.insert ("0", "$"); Json.insert (0, obj); Qjsonobject Obj1;obj1.insert ("1", "111"); Json.insert (1, obj1); Qjsondocument Doc;doc.setarray (JSON); Qbytearray byte = Doc.tojson (Qjsondocument::compact);
Analytical:
Qjsonparseerror error; Qjsondocument doc = Qjsondocument::fromjson (byte, &error); if (Error.error = = qjsonparseerror::noerror) { if (Doc.isarray ()) { Qjsonarray array = Doc.array (); for (int i=0; i<array.size (); i++) { Qjsonvalue value = array.at (i);}} }
QT Parsing and assembly JSON