I have exactly following json data as follows:
[
{
"id":"01323",
"name":"Json Roy",
"contacts":[
"CONTACT1=+917673267299",
"CONTACT2=+917673267292",
"CONTACT3=+917673267293",
"CONTACT4=+917673267294",
]
}
]
I want to parse above jsonData data and extract contacts of that data.
QJsonParseError jerror;
QJsonDocument jsonData = QJsonDocument::fromJson(jsonData.c_str(),&jerror);
QJsonArray jsonArray = jsonData.array();
QJsonObject jsonObject = jsonData.object();
foreach (const QJsonValue & value, jsonArray){
string contact=jsonObject["contacts"].toString().toUtf8().constData();
}
can anybody suggest me how can i accomplish this with same above library?
I removed latest comma in the contacts list.
Your mistake is treating QJsonValue
as you want but QJsonValue
is something like a wrapper so you should convert it to appropriate object ( array, object, string etc. ).
jsonData
is not an object so jsonData.object()
doesn't give you what you want.
Here is the code, it could be the starting point for you.
#include <QString>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonParseError>
#include <QDebug>
#include <string>
int main(){
auto json_input = R"([
{
"id":"01323",
"name":"Json Roy",
"contacts":[
"CONTACT1=+917673267299",
"CONTACT2=+917673267292",
"CONTACT3=+917673267293",
"CONTACT4=+917673267294"
]
}
])";
QJsonParseError err;
auto doc = QJsonDocument::fromJson( QString::fromStdString( json_input ).toLatin1() , &err );
auto objects = doc.array();
if ( err.error != QJsonParseError::NoError )
{
qDebug() << err.errorString();
return 1;
}
for( auto obj_val : objects )
{
auto obj = obj_val.toObject();
auto contacts = obj.value( "contacts" ).toArray();
for ( auto contact_val : contacts )
{
auto cotact_str = contact_val.toString();
qDebug() << cotact_str;
}
}
}
Output :
CONTACT1=+917673267299 CONTACT2=+917673267292 CONTACT3=+917673267293 CONTACT4=+917673267294
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.