【问题标题】:Qjson handling an returned array of ojbectsCjson 处理返回的对象数组
【发布时间】:2012-10-16 06:28:00
【问题描述】:

我正在使用 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( )'

我想学习将这个元素放入类的正确语法。

【问题讨论】:

  • 您的问题似乎是一个 JSON 解析问题。我建议你参考关于json解析的众多教程之一。例如secretgeek.net/json_3mins.asp
  • 我的问题是特定于 Qjson 解析器的。我希望我可以继续使用该解析器。

标签: c++ json qt qjson


【解决方案1】:

更新:我写了另一个函数来将 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))
}

【讨论】:

    猜你喜欢
    • 2014-08-15
    • 2010-12-13
    • 2019-01-13
    • 2021-05-21
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    相关资源
    最近更新 更多