gpt4 book ai didi

c++ - 使用 QVariant Maps 在 Qt 5.7 中使用更简单的方法替换 json 格式的字段

转载 作者:行者123 更新时间:2023-11-30 05:21:43 25 4
gpt4 key购买 nike

我有 3 个从 JSON 创建的 variantMaps,我想替换
例如,从 3d 到 2nd 和 second 到 first 到属性的所有 3 件事。

    QVariantMap wholeMapToChange;         //1.          
QVariantMap propertiesMapToChange; //2.
QVariantMap cmdMap; //3.

第一个包含此 JSON 数据但在 map 中:

{
properties {
"A": true,
"B": true,
"fieldName": "ewfqfqewf",
"C": false,
"fieldPassword": "451541611",
"isBtnSignOnClicked": true
},
type: "xyz"
}

第二个包含此 JSON 数据但在 map 中:

{ 
"A": true,
"B": true,
"fieldName": "ewfqfqewf",
"C": false,
"fieldPassword": "451541611",
"isBtnSignOnClicked": true
}

3d 包含此 JSON 数据但在 map 中:

{ 
"fieldName": "nick",
"fieldPassword": "0000",
"isBtnSignOnClicked": true
}

我认为用 2 替换 3 的可能性是创建循环

for (QVariantMap::const_iterator it = propertiesMapToChange.begin(); it != propertiesMapToChange.end(); ++it){

for (QVariantMap::const_iterator itt = cmdMap.begin(); itt != cmdMap.end(); ++itt){

///here would be the comparig...

}
}

但我认为这不是一个好的解决方案...我想请您提供建议或意见,是否正确,或者是否存在更好的方法。

谢谢

最佳答案

如果 map 不是太大,这是正确的解决方案,因为成本是 N*M。但这是过早的悲观。您应该实现具有 N+M 成本的循环:毕竟 map 是排序的,所以您只需要迭代每个 map 一次。

一个完整的例子:

// https://github.com/KubaO/stackoverflown/tree/master/questions/json-map-iter-39979440
#include <QtCore>

QVariantMap replaceMap(QVariantMap dst, const QVariantMap & src) {
auto dit = dst.begin();
auto sit = src.begin();
while (dit != dst.end() && sit != src.end()) {
if (sit.key() < dit.key()) {
++ sit;
continue;
}
if (dit.key() < sit.key()) {
++ dit;
continue;
}
Q_ASSERT(sit.key() == dit.key());
dit.value() = sit.value();
++ sit;
++ dit;
}
return dst;
}

int main() {
auto json1 = QJsonDocument::fromJson({R"ZZ({
"properties":{
"A":true,
"B":true,
"fieldName":"ewfqfqewf",
"C":false,
"fieldPassword":"451541611",
"isBtnSignOnClicked":true
},
"type":"xyz"
})ZZ"}).toVariant().value<QVariantMap>();

auto json2 = QJsonDocument::fromJson({R"ZZ({
"A":true,
"B":true,
"fieldName":"ewfqfqewf",
"C":false,
"fieldPassword":"451541611",
"isBtnSignOnClicked":true
})ZZ"}).toVariant().value<QVariantMap>();

auto json3 = QJsonDocument::fromJson(
{R"ZZ({
"fieldName":"nick",
"fieldPassword":"0000",
"isBtnSignOnClicked":true
})ZZ"}).toVariant().value<QVariantMap>();

json2 = replaceMap(json2, json3);
auto props = replaceMap(json1["properties"].value<QVariantMap>(), json2);
json1["properties"] = props;

qDebug() << QJsonDocument::fromVariant(json1).toJson().constData();
}

输出:

{
"properties": {
"A": true,
"B": true,
"C": false,
"fieldName": "nick",
"fieldPassword": "0000",
"isBtnSignOnClicked": true
},
"type": "xyz"
}

关于c++ - 使用 QVariant Maps 在 Qt 5.7 中使用更简单的方法替换 json 格式的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39979440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com