Qt之json与xml互相转换

Qt之json与xml互相转换_json

#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QTextStream>

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setWindowTitle(QString::fromLocal8Bit("json xml 文件转换:作者:QQ:609162385"));
}

Widget::~Widget()
{
delete ui;
}

void Widget::json2xmlconvert(const istream &input)
{
ostringstream oss;
oss << input.rdbuf();
std::string xml;
json2xml(oss.str().data(), xml);
std::cout << xml << std::endl;
QString tempstr(xml.c_str());
QFile outFile(json2xml_output_fileName);
outFile.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream ts(&outFile);
ts << tempstr << endl;
}

void Widget::xml2jsonconvert(const istream &input)
{
ostringstream oss;
oss << input.rdbuf();
std::string json;
xml2json(oss.str().data(), json);
std::cout << json << std::endl;

QString tempstr(json.c_str());
QFile outFile(xml2json_output_fileName);
outFile.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream ts(&outFile);
ts << tempstr << endl;
}

void Widget::on_btn_json2xml_clicked()
{
json2xmlconvert(ifstream(json2xml_input_fileName.toStdString().c_str()));
}

void Widget::on_btn_xml2json_clicked()
{
xml2jsonconvert(ifstream(xml2json_input_fileName.toStdString().c_str()));
}

void Widget::on_btn_json2xml_input_clicked()
{
json2xml_input_fileName = QFileDialog::getOpenFileName(this,
tr("Open file"), "/home/jana", tr(" Files (*.json)"));
ui->json2xml_input->setText(json2xml_input_fileName);
}

void Widget::on_btn_json2xml_output_clicked()
{
json2xml_output_fileName = QFileDialog::getSaveFileName(this,
tr("Open file"), "/home/jana", tr(" Files (*.xml)"));
ui->json2xml_output->setText(json2xml_output_fileName);
}

void Widget::on_btn_xml2json_input_clicked()
{
xml2json_input_fileName = QFileDialog::getOpenFileName(this,
tr("Open file"), "/home/jana", tr(" Files (*.xml)"));
ui->xml2json_input->setText(xml2json_input_fileName);
}

void Widget::on_btn_xml2json_output_clicked()
{
xml2json_output_fileName = QFileDialog::getSaveFileName(this,
tr("Open file"), "/home/jana", tr(" Files (*.json)"));
ui->xml2json_output->setText(xml2json_output_fileName);
}
#ifndef WIDGET_H
#define WIDGET_H
#include "../src/j2x.h"
#include <QWidget>
#include <iostream>
#include <sstream>
#include <fstream>
#include <QFileDialog>

using namespace std;
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
Q_OBJECT

public:
explicit Widget(QWidget *parent = 0);
~Widget();
void json2xmlconvert(const istream &input);
void xml2jsonconvert(const istream &input);
private slots:
void on_btn_json2xml_clicked();

void on_btn_xml2json_clicked();

void on_btn_json2xml_input_clicked();

void on_btn_json2xml_output_clicked();

void on_btn_xml2json_input_clicked();

void on_btn_xml2json_output_clicked();

private:
Ui::Widget *ui;
QString json2xml_input_fileName;
QString json2xml_output_fileName;
QString xml2json_input_fileName;
QString xml2json_output_fileName;
};

#endif // WIDGET_H