当前位置:   article > 正文

Qt JSON详解三(读写实例)_qjsondocument::fromjson

qjsondocument::fromjson

QT解析Json格式文件类

  • QJsonDocument  类提供了读写JSON文档的方式,我们可以通过该类的方法QJsonDocument::fromJson()将一个JSON文档转换成QJsonDocument类,或者通过QJsonDocument::toJson()和QJsonDocument::toBinaryData()函数将一个QJsonDocument类转换为QByteArray,这样我们就可以很轻松地将其写入文件。
  • QJsonArray  封装了JSON中的数组。
  • QJsonObject  封装了JSON中的对象。
  • QJsonValue  封装了JSON中的值。
  • QJsonParseError  用于报告JSON解析中的错误类型。

代码示例

1.简单写json

  1. #include <QJsonArray>
  2. #include <QJsonDocument>
  3. #include <QJsonObject>
  4. #include <QJsonParseError>
  5. #include <QJsonValue>
  6. #include <QString>
  7. #include <QDebug>
  8. #include <QFile>
  9. #include <QDateTime>
  10. #include <QDir>
  11. int main(int argc, char *argv[]) {
  12. // 以读写方式打开主目录下的1.json文件,若该文件不存在则会自动创建
  13. QFile file(QDir::homePath() + "/1.json");
  14. if(!file.open(QIODevice::ReadWrite)) {
  15. qDebug() << "File open error";
  16. } else {
  17. qDebug() <<"File open!";
  18. }
  19. // 使用QJsonObject对象插入键值对。
  20. QJsonObject jsonObject;
  21. jsonObject.insert("name", "tom");
  22. jsonObject.insert("age", "18");
  23. jsonObject.insert("time", QDateTime::currentDateTime().toString());
  24. // 使用QJsonDocument设置该json对象
  25. QJsonDocument jsonDoc;
  26. jsonDoc.setObject(jsonObject);
  27. // 将json以文本形式写入文件并关闭文件。
  28. file.write(jsonDoc.toJson());
  29. file.close();
  30. qDebug() << "Write to file";
  31. return 0;
  32. }

2.上面QJsonObject写入是无序的键值对,若要有序则可以使用QJsonArray

  1. #include <QJsonArray>
  2. #include <QJsonDocument>
  3. #include <QJsonObject>
  4. #include <QJsonParseError>
  5. #include <QJsonValue>
  6. #include <QString>
  7. #include <QDebug>
  8. #include <QFile>
  9. #include <QDateTime>
  10. #include <QDir>
  11. int main(int argc, char *argv[]) {
  12. // 以读写方式打开主目录下的1.json文件,若该文件不存在则会自动创建
  13. QFile file(QDir::homePath() + "/1.json");
  14. if(!file.open(QIODevice::ReadWrite)) {
  15. qDebug() << "File open error";
  16. } else {
  17. qDebug() <<"File open!";
  18. }
  19. // 清空文件中的原有内容
  20. file.resize(0);
  21. // 使用QJsonArray添加值,并写入文件
  22. QJsonArray jsonArray;
  23. jsonArray.append("name");
  24. jsonArray.append(18);
  25. jsonArray.append(QDateTime::currentDateTime().toString());
  26. QJsonDocument jsonDoc;
  27. jsonDoc.setArray(jsonArray);
  28. file.write(jsonDoc.toJson());
  29. file.close();
  30. qDebug() << "Write to file";
  31. return 0;
  32. }

3.综合使用

  1. #include <QJsonArray>
  2. #include <QJsonDocument>
  3. #include <QJsonObject>
  4. #include <QJsonParseError>
  5. #include <QJsonValue>
  6. #include <QString>
  7. #include <QDebug>
  8. #include <QFile>
  9. #include <QDateTime>
  10. #include <QDir>
  11. #include <QThread>
  12. int main(int argc, char *argv[]) {
  13. // 以读写方式打开主目录下的1.json文件,若该文件不存在则会自动创建
  14. QFile file(QDir::homePath() + "/1.json");
  15. if(!file.open(QIODevice::ReadWrite)) {
  16. qDebug() << "File open error";
  17. } else {
  18. qDebug() <<"File open!";
  19. }
  20. // 清空文件中的原有内容
  21. file.resize(0);
  22. // 使用QJsonArray添加值,并写入文件
  23. QJsonArray jsonArray;
  24. for(int i = 0; i < 3; i++) {
  25. QJsonObject jsonObject;
  26. jsonObject.insert("name", QString::number(i+1));
  27. jsonObject.insert("age", i+18);
  28. jsonObject.insert("time", QDateTime::currentDateTime().toString());
  29. jsonArray.append(jsonObject);
  30. QThread::sleep(2);
  31. }
  32. QJsonObject jsonObject;
  33. jsonObject.insert("number", jsonArray.size());
  34. jsonArray.append(jsonObject);
  35. QJsonDocument jsonDoc;
  36. jsonDoc.setArray(jsonArray);
  37. file.write(jsonDoc.toJson());
  38. file.close();
  39. qDebug() << "Write to file";
  40. return 0;
  41. }

4.读取实例1

json文件:

  1. {
  2. "first fruit":
  3. {
  4. "describe":"an apple",
  5. "icon":"appleIcon",
  6. "name":"apple"
  7. },
  8. "second fruit":
  9. {
  10. "describe":"an orange",
  11. "icon":"orangeIcon",
  12. "name":"orange"
  13. },
  14. "three fruit array":
  15. [
  16. "eat 0",
  17. "eat 1",
  18. "eat 2",
  19. "eat 3",
  20. "eat 4"
  21. ]
  22. }

读取代码:

  1. //打开文件
  2. QFile loadFile("D:\\1.json");
  3. if(!loadFile.open(QIODevice::ReadOnly))
  4. {
  5. qDebug() << "could't open projects json";
  6. return;
  7. }
  8. //读取文件内容
  9. QByteArray allData = loadFile.readAll();
  10. loadFile.close();
  11. //以json格式读取内容到JsonDoc
  12. QJsonParseError jsonError;
  13. QJsonDocument jsonDoc(QJsonDocument::fromJson(allData, &jsonError));
  14. if(jsonError.error != QJsonParseError::NoError)
  15. {
  16. qDebug() << "json error!" << jsonError.errorString();
  17. return;
  18. }
  19. //创建jsonObject
  20. QJsonObject rootObj = jsonDoc.object();
  21. QStringList keys = rootObj.keys();
  22. for(int i = 0; i < keys.size(); i++)
  23. {
  24. qDebug() << "key" << i << " is:" << keys.at(i);
  25. }
  26. //因为是预先定义好的JSON数据格式,所以这里可以这样读取
  27. if(rootObj.contains("first fruit"))
  28. {
  29. QJsonObject subObj = rootObj.value("first fruit").toObject();
  30. qDebug() << "describe is:" << subObj["describe"].toString();
  31. qDebug() << "icon is:" << subObj["icon"].toString();
  32. qDebug() << "name is:" << subObj["name"].toString();
  33. }
  34. if(rootObj.contains("second fruit"))
  35. {
  36. QJsonObject subObj = rootObj.value("second fruit").toObject();
  37. qDebug() << "describe is:" << subObj.value("describe").toString();
  38. qDebug() << "icon is:" << subObj.value("icon").toString();
  39. qDebug() << "name is:" << subObj.value("name").toString();
  40. }
  41. if(rootObj.contains("three fruit array"))
  42. {
  43. QJsonArray subArray = rootObj.value("three fruit array").toArray();
  44. for(int i = 0; i< subArray.size(); i++)
  45. {
  46. qDebug() << i<<" value is:" << subArray.at(i).toString();
  47. }
  48. }

5.读取实例2

json文件:

  1. {
  2. //头部
  3. "header":
  4. {
  5. "mapType":"2D-Map",
  6. "mapName":"2",
  7. "minPos":{"x":-5.132,"y":-0.158},
  8. "maxPos":{"x":18.256,"y":10.86},
  9. "resolution":0.02,
  10. "version":"1.0.6"
  11. },
  12. //普通点集合
  13. "normalPosList":
  14. [
  15. {"x":-0.006,"y":8.199},
  16. {"x":-0.006,"y":8.219},
  17. {"x":-0.007,"y":8.119},
  18. //...
  19. ],
  20. //高级点集合
  21. "advancedPointList":
  22. [
  23. {
  24. "className":"LandMark",
  25. "instanceName":"LM1",
  26. "pos":{"x":16.344,"y":6.621},
  27. "property":
  28. [
  29. {"key":"spin","type":"bool","value":"ZmFsc2U=","boolValue":false}
  30. ]
  31. },
  32. {
  33. "className":"LandMark",
  34. "instanceName":"LM2",
  35. "pos":{"x":3.693,"y":6.621},
  36. "dir":-3.1415926535897931,
  37. "property":[{"key":"spin","type":"bool","value":"ZmFsc2U=","boolValue":false}]
  38. }
  39. ],
  40. //曲线集合
  41. "advancedCurveList":
  42. [
  43. {
  44. "className":"BezierPath",
  45. "instanceName":"LM1-LM2",
  46. "startPos":
  47. {
  48. "instanceName":"LM1",
  49. "pos":{"x":16.344,"y":6.621}
  50. },
  51. "endPos":
  52. {
  53. "instanceName":"LM2",
  54. "pos":{"x":3.693,"y":6.621}
  55. },
  56. "controlPos1":{"x":12.127,"y":6.621},
  57. "controlPos2":{"x":7.91,"y":6.621},
  58. "property":
  59. [
  60. {"key":"direction","type":"int","value":"MA==","int32Value":0},
  61. {"key":"movestyle","type":"int","value":"MA==","int32Value":0}
  62. ]
  63. }
  64. ]
  65. }

解析代码:

  1. void MainWindow::handleJsonFile(QString FilePath)
  2. {
  3. //打开读取文件内容
  4. QFile file(FilePath);
  5. if(file.exists())
  6. file.open(QIODevice::ReadOnly);
  7. else return;
  8. QByteArray data = file.readAll();
  9. file.close();
  10. //json文件转换成对象
  11. QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
  12. QJsonObject jsonObject = jsonDoc.object();
  13. //列出json里的所有key
  14. QStringList keys = jsonObject.keys();
  15. for(int i=0;i<keys.size();++i)
  16. qDebug()<<"key "<<i<<" is "<<keys.at(i);
  17. //放大倍率
  18. int mulriple = 40;
  19. //根据key进行相应操作
  20. if(keys.contains("header"))
  21. {
  22. //获取属性信息
  23. QJsonObject JOB_header = jsonObject["header"].toObject();
  24. QString mapType = JOB_header["mapType"].toString();
  25. QString mapName = JOB_header["mapName"].toString();
  26. QString mapVersion = JOB_header["version"].toString();
  27. double resolution = JOB_header["resolution"].toDouble();
  28. //打印map属性
  29. ui->PTEInfo->clear();
  30. ui->PTEInfo->appendPlainText(QString("mapType: ")+mapType);
  31. ui->PTEInfo->appendPlainText(QString("mapName: ")+mapName);
  32. ui->PTEInfo->appendPlainText(QString("mapVersion: ")+mapVersion);
  33. ui->PTEInfo->appendPlainText(QString("resolution: %1").arg(resolution));
  34. //获取场景大小信息
  35. QJsonObject JOB_minPos = JOB_header["minPos"].toObject();
  36. QJsonObject JOB_maxPos = JOB_header["maxPos"].toObject();
  37. qreal scenePosX = JOB_minPos["x"].toDouble()*mulriple;
  38. qreal scenePosY = JOB_minPos["y"].toDouble()*mulriple;
  39. qreal sceneEdgeX = JOB_maxPos["x"].toDouble()*mulriple;
  40. qreal sceneEdgeY = JOB_maxPos["y"].toDouble()*mulriple;
  41. qreal sceneWidth = sceneEdgeX - scenePosX;
  42. qreal sceneHight = sceneEdgeY - scenePosY;
  43. scene = new QGraphicsScene(scenePosX,scenePosY,sceneWidth,sceneHight);
  44. //添加场景,并显示矩形框
  45. ui->graphicsView->setScene(scene);
  46. scene->addRect(scenePosX,scenePosY,scene->width(),scene->height());
  47. }
  48. //显示普通点
  49. if(keys.contains("normalPosList"))
  50. {
  51. QJsonArray posArray = jsonObject["normalPosList"].toArray();
  52. //绘制点
  53. for(auto i : posArray){
  54. QJsonObject JOB_pos = i.toObject();
  55. qreal x = JOB_pos["x"].toDouble()*mulriple;
  56. qreal y = JOB_pos["y"].toDouble()*mulriple;
  57. scene->addEllipse(x,y,1,1);
  58. }
  59. }
  60. //显示高级点
  61. if(keys.contains("advancedPointList"))
  62. {
  63. QJsonArray APosArray = jsonObject["advancedPointList"].toArray();
  64. int AposCount = APosArray.count();
  65. ui->PTEInfo->appendPlainText(QString("LandMarks Num: %1").arg(AposCount));
  66. //绘制高级点
  67. for(auto i : APosArray){
  68. QJsonObject JOB_Apos = i.toObject();
  69. QString className = JOB_Apos["className"].toString();
  70. QString instanceName = JOB_Apos["instanceName"].toString();
  71. QJsonObject JOB_pos = JOB_Apos["pos"].toObject();
  72. qreal x = JOB_pos["x"].toDouble()*mulriple;
  73. qreal y = JOB_pos["y"].toDouble()*mulriple;
  74. QGraphicsItem* item_Apos = scene->addRect(x-10,y-10,20,20,QPen(QColor(Qt::yellow)),QBrush(QColor(Qt::blue)));
  75. //将他加入可编辑图元列表里
  76. this->items_editable.append(item_Apos);
  77. //若标明方向,则绘制方向
  78. if(JOB_Apos.keys().contains("dir")){
  79. qreal angle = JOB_Apos["dir"].toDouble()*180/3.14;
  80. QVector<QPointF> Tri = {{x,y-10},{x+10,y},{x,y+10}};
  81. QGraphicsItem* item_pos_dir = scene->addPolygon(QPolygonF(Tri),QPen(QColor(Qt::red)),QBrush(QColor(Qt::red)));
  82. //设置旋转中心
  83. item_pos_dir->setTransformOriginPoint(x,y);
  84. item_pos_dir->setRotation(angle);
  85. item_pos_dir->setParentItem(item_Apos);
  86. }
  87. }
  88. }
  89. //显示曲线
  90. if(keys.contains("advancedCurveList"))
  91. {
  92. QJsonArray CurArray = jsonObject["advancedCurveList"].toArray();
  93. for(auto i : CurArray){
  94. QJsonObject JOB_Cur = i.toObject();
  95. QJsonObject JOB_Cur_startPos = JOB_Cur["startPos"].toObject();
  96. QJsonObject JOB_Cur_endPos = JOB_Cur["endPos"].toObject();
  97. QJsonObject startPos = JOB_Cur_startPos["pos"].toObject();
  98. qreal x1 = startPos["x"].toDouble()*mulriple;
  99. qreal y1 = startPos["y"].toDouble()*mulriple;
  100. QJsonObject endPos = JOB_Cur_endPos["pos"].toObject();
  101. qreal x2 = endPos["x"].toDouble()*mulriple;
  102. qreal y2 = endPos["y"].toDouble()*mulriple;
  103. QJsonObject controlPos1 = JOB_Cur["controlPos1"].toObject();
  104. qreal cx1 = controlPos1["x"].toDouble()*mulriple;
  105. qreal cy1 = controlPos1["y"].toDouble()*mulriple;
  106. QJsonObject controlPos2 = JOB_Cur["controlPos2"].toObject();
  107. qreal cx2 = controlPos2["x"].toDouble()*mulriple;
  108. qreal cy2 = controlPos2["y"].toDouble()*mulriple;
  109. //画贝塞斯曲线
  110. //绘制贝塞斯曲线路径,初始化输入起始点,然后设置曲线的两个控制点和结束点
  111. QPainterPath CurPath(QPointF(x1,y1));
  112. CurPath.cubicTo(QPointF(cx1,cy1),QPointF(cx2,cy2),QPointF(x2,y2));
  113. scene->addPath(CurPath,QPen(QColor(Qt::darkGreen)));
  114. }
  115. }
  116. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/1016485
推荐阅读
相关标签
  

闽ICP备14008679号