软件环境:QT Version 5.14.0
1.目标
问题背景:鸿蒙OS组件开发需求:解析JS层后并绘制一段折现;基于此背景利用qt框架下的JSON解析模块实现此需求。此案例仅仅是对qt框架的一个json模块探索,与实际工作内容无关。
1.利用qt json模块解析json文件,实现对一组数据点point的解析
2.对解析出的点并绘制一段折线,本文不涉及此内容,感兴趣可以自己补充实现
2.JSON文件
{
“points”: [
[ 10, 20 ],
[ 10, 30 ],
[ 10, 50 ]
]
}
3.代码结构
4.代码示例
Point.h
#ifndef POINT_H
#define POINT_H
#include<iostream>
#include<utility>
#include<QVector>
#include<QPair>
#include<QPoint>
using Points = QVector<QPoint>;
#endif // POINT_H
Polyline.h
#ifndef SHAPE_POINT_H
#define SHAPE_POINT_H
#include"Point.h"
class Shape_Point
{
public:
Shape_Point();
void SetPoints(Points& points);
Points& GetPoints();
void PaintPoint();
private:
//point contain x value and y value;
//Point point;
QPoint point;
//vector contain all parse points;
Points points;
};
#endif // SHAPE_POINT_H
Polyline.cpp
#include "Polyline.h"
#include<QDebug>
Shape_Point::Shape_Point():point(0,0)
{
}
void Shape_Point::SetPoints(Points& points)
{
this->points=points;
}
Points& Shape_Point::GetPoints()
{
return this->points;
}
void Shape_Point::PaintPoint()
{
int size=points.size();
for(int i=0;i<size;i++){
qDebug()<<points[i].x()<<" "<<points[i].y();
}
}
main.cpp
#include <QCoreApplication>
#include <QJsonObject>
#include <QJsonObject>
#include<QJsonArray>
#include<Polyline.h>
#include<QFile>
#include<QDebug>
#include<QTextStream>
#include<QJsonDocument>
/*
{
"points":[[10,20],[10,30]]
}
*/
/*in order to parse points to vector*/
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("F:\\QT Project\\Json_1\\json.json");
if(!file.open(QIODevice::ReadOnly)){
qDebug()<<"open error";
}
QByteArray byteArr=file.readAll();
QString jsonStr=QString(byteArr);
qDebug()<<jsonStr;
//parse json points
QJsonParseError err;
QJsonDocument doc=QJsonDocument::fromJson(byteArr,&err);
QJsonObject rootobj=doc.object();
Shape_Point polyline_point;
Points points_;
QPoint point;
QJsonValue pointsValue=rootobj.value("points");
if(pointsValue.type()==QJsonValue::Array){
QJsonArray pointsArr=pointsValue.toArray();
for(int i=0;i<pointsArr.count();i++){
QJsonValue pointsValue=pointsArr.at(i);
if(pointsValue.type()==QJsonValue::Array ){
QJsonArray pointsArr=pointsValue.toArray();
if(pointsArr.size()>=2){
point.setX(pointsArr.at(0).toInt());
point.setY(pointsArr.at(1).toInt());
points_.push_back(point);
}
}
}
polyline_point.SetPoints(points_);
}
//print polyline's all points;
polyline_point.PaintPoint();
return a.exec();
}
5.运行效果
6.思考
如果QT框架中没有实现点的定义(Qpoint),又该如何实现此需求?
参考我的另一篇文章:
链接: link.