forked from EEEugene/qtWeatherForecast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
weatherTool.h
62 lines (53 loc) · 1.61 KB
/
weatherTool.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#ifndef WEATHERTOOL_H
#define WEATHERTOOL_H
#include <QMap>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonParseError>
#include <QJsonValue>
class WeatherTool{
private:
static QMap<QString,QString> mCityMaps;
static void initCityMap(){
QString filePath = "D:/citycode-2019-08-23.json";
QFile file(filePath);
file.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray json = file.readAll();
file.close();
QJsonParseError err;
QJsonDocument doc = QJsonDocument::fromJson(json,&err);
if(err.error != QJsonParseError::NoError){
return;
}
if(!doc.isArray()){
return;
}
QJsonArray cities = doc.array();
for(int i = 0;i <cities.size();i++){
QString city = cities[i].toObject().value("city_name").toString();
QString code = cities[i].toObject().value("city_code").toString();
if(code.size() > 0){
mCityMaps.insert(city,code);
}
}
}
public:
static QString getCityCode(QString cityName){
if(mCityMaps.isEmpty()){
initCityMap();
}
QMap<QString,QString>::iterator it = mCityMaps.find(cityName);
//
if(it == mCityMaps.end()){
it = mCityMaps.find(cityName + "市");
}
if(it != mCityMaps.end()){
return it.value();
}
return "";
}
};
QMap<QString,QString> WeatherTool::mCityMaps={};
#endif // WEATHERTOOL_H