我使用Qjson来解析从web服务返回的json对象。我被困在处理复杂对象的数组上。
在第一级,web服务返回一个由"error“、"id”和"return“组成的映射。如果没有错误,我可以通过使用以下命令获得第一级值
nestedMap = m_jsonObject["result"].toMap();
group = new Group();
group->Caption = nestedMap["Caption"].toString();
group->CollectionCount = nestedMap["CollectionCount"].toInt();我甚至可以使用下面的命令获得第二级的日期项值
group->ModifiedOn = nestedMap["ModifiedOn"].toMap()["Value"].toDateTime();我有一个名为"Elements“的对象,它由29个键值对组成。web服务返回这些“元素”的数组,但我找不到正确的方法来解析它。在头文件中,元素的容器定义为
QList<GroupElement> Elements;这条线
group->Elements = nestedMap["Elements"].toList();导致编译器引发错误“error : no match for 'operator=‘in '((MyClass*)this)->MyClass::group->Group::Elements = QVariant::toMap() const()”
我想学习将这个元素放入类中的正确语法。
发布于 2012-10-27 09:28:52
更新:我编写了另一个函数来将QVariantMap对象转换为
首先: group-> Elements对象被更改为
class ParentClass{
QList<SharedDataPointer<Address> > Elements;
other class memmbers...
};第二:创建了一个将QMap对象转换为Address对象的方法
QSharedDataPointer<Address>
API_1_6::mapToAddress(QVariantMap o)
{
QSharedDataPointer<Address> address (new Address());
address-> FirstName = o["FirstName"].toString();
address->LastName = o["LastName"].toString();
address->CompanyName = o["CompanyName"].toString();
address->Street = o["Street"].toString();
address->Street2 = o["Street2"].toString();
address->City = o["City"].toString();
address->Zip = o["Zip"].toString();
address-> State = o["State"].toString();
address->Country = o["Country"].toString();
address->Phone = o["Phone"].toString();
address->Phone2 = o["Phone2"].toString();
address-> Fax = o["Fax"].toString();
address-> Url = o["Url"].toString();
address->Email = o["Email"].toString();
address->Other = o["Other"].toString();
return address;
}第三:在代码中,foreach用于遍历列表并创建和存储新对象
// get the list of the elements
elementsList = nestedMap["Elements"].toList();
// Add the element, converted to the new type, to the Elements object of the'parent' class
foreach(QVariant qElement, elementsList){
group-> Elements.append(mapToAddress(qElement))
}https://stackoverflow.com/questions/12908728
复制相似问题