У меня есть графическая программа для чтения XML-файлов, я написал 2 функции для преобразования XML в JSON, но при преобразовании почему-то теряется значение последнего элемента. Прикрепленное изображение показывает мой исходный XML и полученный из него JSON.
Как это можно исправить?
Вот мои методы:
QJsonObject QtXML::modelIndexToJson(const QModelIndex &index,
QtTreeModel *model) {
QJsonObject jsonObject;
// Get the node name
QString key = model->data(index, Qt::DisplayRole).toString();
// Check if there is a text value
QString value = model->data(index, Qt::EditRole).toString();
// If there is a text value, save it
if (!value.isEmpty()) {
jsonObject[key] = value;
} else {
// If there is no text value, process child elements
QJsonObject childrenObject;
for (int i = 0; i < model->rowCount(index); ++i) {
QModelIndex childIndex = model->index(i, 0, index);
childrenObject.insert(model->data(childIndex, Qt::DisplayRole).toString(),
modelIndexToJson(childIndex, model));
}
jsonObject[key] = childrenObject;
}
return jsonObject;
}
// Method to convert data from QTreeView to JSON and save it to a file
void QtXML::convertXmlToJson(const QString &jsonFilePath) {
// Get the current view (QTreeView) from the tab
auto *currView = qobject_cast(tabWgt->currentWidget());
if (!currView) {
qWarning("The current view is not a QTreeView.");
return;
}
// Get the model of the current view
auto *currModel = dynamic_cast(currView->model());
if (!currModel) {
qWarning("The current view's model is not a QtTreeModel.");
return;
}
// Convert the root elements of the model into JSON
QJsonObject rootObject;
for (int i = 0; i < currModel->rowCount(); ++i) {
QModelIndex rootIndex = currModel->index(i, 0);
rootObject.insert(currModel->data(rootIndex, Qt::DisplayRole).toString(),
modelIndexToJson(rootIndex, currModel));
}
// Create JSON document
QJsonDocument jsonDoc(rootObject);
// Write JSON to file
QFile jsonFile(jsonFilePath);
if (!jsonFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qWarning("Failed to open JSON file for writing");
return;
}
jsonFile.write(jsonDoc.toJson(QJsonDocument::Indented));
jsonFile.close();
qInfo("Data from QTreeView successfully converted to JSON and written to file");
}
Пример работы методов. Исходный XML-файл:
Attraction registered
1058514543
77-0234
68350f83-f3d1-49e1-bdfc-739647cea2df
4
55.7875
37.6560
Park
Sokolniki District
Happy Swing
Eastern Administrative Okrug
SOKOLNIKI CULTURE AND RECREATION PARK
Преобразованный файл JSON:
{
"ex.xml": {
"ex.xml": {
"Happy Swing": {
"Happy Swing": {
"AdmArea": {
"AdmArea": {
"": {
"": {
}
}
}
},
"District": {
"District": {
"": {
"": {
}
}
}
},
"ID": {
"ID": {
"": {
"": {
}
}
}
},
"Location": {
"Location": {
"": {
"": {
}
}
}
},
"LocationType": {
"LocationType": {
"": {
"": {
}
}
}
},
"Name": {
"Name": {
"": {
"": {
}
}
}
},
"Photo": {
"Photo": {
"": {
"": {
}
}
}
},
"RegistrationNumber": {
"RegistrationNumber": {
"": {
"": {
}
}
}
},
"State": {
"State": {
"": {
"": {
}
}
}
},
"geoData": {
"geoData": {
"Latitude": {
"Latitude": {
"": {
"": {
}
}
}
},
"Longitude": {
"Longitude": {
"": {
"": {
}
}
}
}
}
},
"global_id": {
"global_id": {
"": {
"": {
}
}
}
}
}
}
}
}
}
Ожидаемый файл JSON:
{
"catalog": {
"array": {
"State": "Attraction registered",
"global_id": 1058514543,
"RegistrationNumber": "77-0234",
"Photo": "68350f83-f3d1-49e1-bdfc-739647cea2df",
"ID": 4,
"geoData": {
"Latitude": 55.7875,
"Longitude": 37.656
},
"LocationType": "Park",
"District": "Sokolniki District",
"Name": "Happy Swing",
"AdmArea": "Eastern Administrative Okrug",
"Location": "SOKOLNIKI CULTURE AND RECREATION PARK"
}
}
}
Это мой QtTreeModel.h:
class QtTreeModel : public QAbstractItemModel {
Q_OBJECT
public:
QtTreeModel(QObject *parent = nullptr);
void append(const QModelIndex &index);
void read(const QString &fileName);
void parseDomNode(const QDomNode &node, QStandardItem *parentItem);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &index) const override;
QVariant data(const QModelIndex &index,
int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
bool removeRows(int row, int count,
const QModelIndex &parent = QModelIndex()) override;
void removeFile(const QString &fileName);
QStringList getFileList() const;
void setFileList(const QStringList &newFiles);
void addFile(const QString &fileName);
void clearFileList();
QStandardItem *getRoot() const { return root; }
private:
QStringList files{};
QStandardItem *root{};
QModelIndex currIndex{};
void append(const QModelIndex &sourceIndex, QStandardItem *item);
};
Подробнее здесь: https://stackoverflow.com/questions/793 ... conversion
Проблема с преобразованием XML в JSON. ⇐ C++
Программы на C++. Форум разработчиков
1735880853
Anonymous
У меня есть графическая программа для чтения XML-файлов, я написал 2 функции для преобразования XML в JSON, но при преобразовании почему-то теряется значение последнего элемента. Прикрепленное изображение показывает мой исходный XML и полученный из него JSON.
Как это можно исправить?
Вот мои методы:
QJsonObject QtXML::modelIndexToJson(const QModelIndex &index,
QtTreeModel *model) {
QJsonObject jsonObject;
// Get the node name
QString key = model->data(index, Qt::DisplayRole).toString();
// Check if there is a text value
QString value = model->data(index, Qt::EditRole).toString();
// If there is a text value, save it
if (!value.isEmpty()) {
jsonObject[key] = value;
} else {
// If there is no text value, process child elements
QJsonObject childrenObject;
for (int i = 0; i < model->rowCount(index); ++i) {
QModelIndex childIndex = model->index(i, 0, index);
childrenObject.insert(model->data(childIndex, Qt::DisplayRole).toString(),
modelIndexToJson(childIndex, model));
}
jsonObject[key] = childrenObject;
}
return jsonObject;
}
// Method to convert data from QTreeView to JSON and save it to a file
void QtXML::convertXmlToJson(const QString &jsonFilePath) {
// Get the current view (QTreeView) from the tab
auto *currView = qobject_cast(tabWgt->currentWidget());
if (!currView) {
qWarning("The current view is not a QTreeView.");
return;
}
// Get the model of the current view
auto *currModel = dynamic_cast(currView->model());
if (!currModel) {
qWarning("The current view's model is not a QtTreeModel.");
return;
}
// Convert the root elements of the model into JSON
QJsonObject rootObject;
for (int i = 0; i < currModel->rowCount(); ++i) {
QModelIndex rootIndex = currModel->index(i, 0);
rootObject.insert(currModel->data(rootIndex, Qt::DisplayRole).toString(),
modelIndexToJson(rootIndex, currModel));
}
// Create JSON document
QJsonDocument jsonDoc(rootObject);
// Write JSON to file
QFile jsonFile(jsonFilePath);
if (!jsonFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qWarning("Failed to open JSON file for writing");
return;
}
jsonFile.write(jsonDoc.toJson(QJsonDocument::Indented));
jsonFile.close();
qInfo("Data from QTreeView successfully converted to JSON and written to file");
}
Пример работы методов. Исходный XML-файл:
Attraction registered
1058514543
77-0234
68350f83-f3d1-49e1-bdfc-739647cea2df
4
55.7875
37.6560
Park
Sokolniki District
Happy Swing
Eastern Administrative Okrug
SOKOLNIKI CULTURE AND RECREATION PARK
Преобразованный файл JSON:
{
"ex.xml": {
"ex.xml": {
"Happy Swing": {
"Happy Swing": {
"AdmArea": {
"AdmArea": {
"": {
"": {
}
}
}
},
"District": {
"District": {
"": {
"": {
}
}
}
},
"ID": {
"ID": {
"": {
"": {
}
}
}
},
"Location": {
"Location": {
"": {
"": {
}
}
}
},
"LocationType": {
"LocationType": {
"": {
"": {
}
}
}
},
"Name": {
"Name": {
"": {
"": {
}
}
}
},
"Photo": {
"Photo": {
"": {
"": {
}
}
}
},
"RegistrationNumber": {
"RegistrationNumber": {
"": {
"": {
}
}
}
},
"State": {
"State": {
"": {
"": {
}
}
}
},
"geoData": {
"geoData": {
"Latitude": {
"Latitude": {
"": {
"": {
}
}
}
},
"Longitude": {
"Longitude": {
"": {
"": {
}
}
}
}
}
},
"global_id": {
"global_id": {
"": {
"": {
}
}
}
}
}
}
}
}
}
Ожидаемый файл JSON:
{
"catalog": {
"array": {
"State": "Attraction registered",
"global_id": 1058514543,
"RegistrationNumber": "77-0234",
"Photo": "68350f83-f3d1-49e1-bdfc-739647cea2df",
"ID": 4,
"geoData": {
"Latitude": 55.7875,
"Longitude": 37.656
},
"LocationType": "Park",
"District": "Sokolniki District",
"Name": "Happy Swing",
"AdmArea": "Eastern Administrative Okrug",
"Location": "SOKOLNIKI CULTURE AND RECREATION PARK"
}
}
}
Это мой QtTreeModel.h:
class QtTreeModel : public QAbstractItemModel {
Q_OBJECT
public:
QtTreeModel(QObject *parent = nullptr);
void append(const QModelIndex &index);
void read(const QString &fileName);
void parseDomNode(const QDomNode &node, QStandardItem *parentItem);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &index) const override;
QVariant data(const QModelIndex &index,
int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
bool removeRows(int row, int count,
const QModelIndex &parent = QModelIndex()) override;
void removeFile(const QString &fileName);
QStringList getFileList() const;
void setFileList(const QStringList &newFiles);
void addFile(const QString &fileName);
void clearFileList();
QStandardItem *getRoot() const { return root; }
private:
QStringList files{};
QStandardItem *root{};
QModelIndex currIndex{};
void append(const QModelIndex &sourceIndex, QStandardItem *item);
};
Подробнее здесь: [url]https://stackoverflow.com/questions/79323899/poblem-with-xml-to-json-conversion[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия