#include <QStringList>
#include <QJsonArray>
#include <QJSonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QFile>
#include <QDebug>
#include "test.h"
#define STR(o) #o
#define INSERT_ITEM(object,o) object.insert(STR(o),o);
#define INSERT_LIST(object,o)\
{\
auto array = QJsonArray::fromStringList(o);\
object.insert(STR(o),array);\
}
struct Unit
{
QString result;
QString author;
QString description;
QString notes;
QStringList key;
int minValue;
QStringList items;
QStringList attachment;
QString toString()
{
QJsonObject object;
INSERT_ITEM(object,result)
INSERT_ITEM(object,author)
INSERT_ITEM(object,description)
INSERT_ITEM(object,notes)
INSERT_LIST(object,key)
INSERT_ITEM(object,minValue)
INSERT_LIST(object,items)
INSERT_LIST(object,attachment)
QJsonDocument doc;
doc.setObject(object);
return doc.toJson(QJsonDocument::JsonFormat::Compact);
}
bool loadFromFile(const QString& filename)
{
QFile file(filename);
if(!file.open(QIODevice::ReadOnly))
return false;
QByteArray buffer = file.readAll();
file.close();
QJsonParseError error;
QJsonDocument doc(QJsonDocument::fromJson(buffer,&error));
if(error.error != QJsonParseError::NoError)
{
qDebug() << "parse json file:"<<filename<< " failed!";
return false;
}
auto object = doc.object();
if(!object.contains("result") || !object.contains("key"))
{
qDebug() << "invalid json file:" << filename << " structure!";
return false;
}
result = object[STR(result)].toString();
author = object[STR(author)].toString();
description = object[STR(description)].toString();
notes = object[STR(notes)].toString();
minValue = object[STR(minValue)].toInt();
auto fn = [](const QJsonArray& array)->QStringList
{
QStringList items;
foreach(auto item,array)
items += item.toString();
return items;
};
key = fn(object[STR(key)].toArray());
items = fn(object[STR(items)].toArray());
attachment = fn(object[STR(attachment)].toArray());
return true;
}
};
void test()
{
Unit unit;
unit.attachment.append("acchemtn1");
unit.attachment.append("acchemtn2");
unit.key.append("key1");
unit.author = "author";
unit.description = "this is a remark";
unit.items.append("item1");
unit.items.append("item2");
unit.items.append("item3");
unit.minValue = 1;
unit.notes = "notes";
QFile file("file.json");
file.open(QIODevice::WriteOnly);
file.write(unit.toString().toLocal8Bit().data());
file.close();
qDebug() << unit.toString();
}