说明
QJsonDocument并不会直接操作文件,需要自行利用QFile进行readAll或者Write;
读取文件
利用Qml的读写文件的操作将Json格式的文件内容传给QJsonDocument就可以操作了
void UDP::analysisJson()
{
FileObject fo;
QJsonParseError error;
//读取文件
QJsonDocument _json = QJsonDocument::fromJson(fo.readFile().toUtf8(),
&error);
//判断错误
if (error.error == QJsonParseError::NoError)
{
auto json_text = _json.toJson(QJsonDocument::Indented);
auto json_binary = _json.toBinaryData();
QJsonDocument read1 = QJsonDocument::fromJson(json_text);
QJsonDocument read2 = QJsonDocument::fromBinaryData(json_binary);
//验证
if (QString(read1.toBinaryData()) == QString(read2.toBinaryData()))
{
qDebug() << "相同";
//判断是否为空
if (read1.isEmpty())
{
qDebug() << "空的";
return;
}
//解析
if (read1.isObject())
{
auto read_object = read1.object();
if (!read_object.isEmpty())
{
qDebug() <<
read_object.value("targetDataGenerationTimestamp").toInt();
qDebug() <<
read_object.value("targetAttribute").toInt();
//qDebug()<<read_object.value("null").isNull();
QJsonValue value =
read_object.value("targetSpeed");
// qDebug()<<value.type()<<value;
if (value.isArray())
{
auto read_array = value.toArray();
for (auto one_of_array : read_array)
{
// qDebug()<<one_of_array;
}
}
}
}
}
}
}
写文件
void UDP::buildJson()
{
//构建json文档
QJsonDocument json;
QJsonObject object;
QJsonArray targetSpeed;
QJsonArray targetLocal;
QJsonArray targetAngle;
//目标数量
object.insert("targetNumber", 2);
//目标名字
object.insert("targetName", "liehuo");
//目标属性
object.insert("targetAttribute", 2);
//目标类型
object.insert("targetType", 1);
//目标实例编号
object.insert("targetInstanceNumber", 857);
//目标所属型号编号
object.insert("targetModelNumber", 15);
//目标子目标实例编号
object.insert("targetSonInstanceNumber", 159);
//目标子类型编号
object.insert("targetSonModelNumber", 11);
//目标子类型规格编号
object.insert("targetSonModelSpecificationNumber", 19);
//目标飞行时间
object.insert("targetFlightTime", 65146514);
//目标数据生成时间戳
object.insert("targetDataGenerationTimestamp", 1519264);
//目标位置
targetLocal.append(123);//x
targetLocal.append(456);//y
targetLocal.append(789);//z
object.insert("targetLocal", targetLocal);
//目标速度
targetSpeed.append(555);//xspeed
targetSpeed.append(888);//yspeed
targetSpeed.append(999);//zspeed
object.insert("targetSpeed", targetSpeed);
//目标1偏航角
targetAngle.append(2236);//偏航角
targetAngle.append(2165);//俯仰角
targetAngle.append(1595);//滚转角
object.insert("targetAngle", targetAngle);
//最外层是大括号所以是object
json.setObject(object);
qDebug() << json.toJson(QJsonDocument::Indented);
fo.writeFile(json.toJson(QJsonDocument::Indented));
}