c++ - QT5 JSON parsing from QByteArray -
i have qbytearray,contains json
{"response": {"count":2, "items":[ {"name":"somename","key":1"}, {"name":"somename","key":1"} ]}}
need parse , required data:
qjsondocument itemdoc = qjsondocument::fromjson(answer); qjsonobject itemobject = itemdoc.object(); qdebug()<<itemobject; qjsonarray itemarray = itemobject["response"].toarray(); qdebug()<<itemarray;
first debug displays contents of qbytearray, recorded in itemobject, second debug not display anything.
must parse otherwise,or why method not work?
you either need know format, or work out asking object type. why qjsonvalue has functions such isarray, toarray, isbool, tobool, etc.
if know format, can this: -
// root object qjsondocument itemdoc = qjsondocument::fromjson(answer); qjsonobject rootobject = itemdoc.object(); // response object qjsonvalue response = rootobject.value("response"); qjsonobject responseobj = response.toobject(); // print out list of keys ("count") qstringlist keys = responseobj.keys(); foreach(qstring key, keys) { qdebug() << key; } // print value of key "count") qdebug() << responseobj.value("count"); // array of items qjsonobject itemarrayobj = responseobj.value("items"); // check have array if(itemarrayobj.isarray()) { // array jsonarray qjsonarray itemarray = itemarrayobj.toarray(); }
if don't know format, you'll have ask each qjsonobject of type , react accordingly. it's idea check type of qjsonvalue before converting rightful object such array, int etc.
Comments
Post a Comment