Qt读取JSON和XML数据

来源:互联网 发布:公司网络管理方案 编辑:程序博客网 时间:2024/06/08 18:35



QJSON

JSON(JavaScript Object Notation)是一个轻量级的数据交换格式; 可以将数据以name/value的形式任意组合;

QJson 是一个基于Qt的库, 将JSON的数据map成name-QVariant的形式, 或者进行反相转换; 通过Q_PROPERTY还可以转换QObject类中的数据;

QJSON Source http://qjson.sourceforge.net/ (需要编译lib来link)


Build 测试时在Windows下进行, 所以我尝试用UI的方式编译: 
1. 用QtCreator打开CMakeList.txt, 进行Configure; 
2. 生成了qjson项目, Build All 

Note 这里有个error, '_strtoui64' was not declared in this scope, 是作者在修VS2012的bug时introduce的, 只要找到json_scanner.cc, 把strtoll和strtoull两个宏注释掉就行;

3. 在Qt项目中引入QJSN的library, QJSON对QtCore有dependency. 
LIBS += -L"PathToQJSONLib" -l"qjson"

e.g. 格式: String必须用"" 包括起来, 使用"\"来转义字符;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
QString query("{\"name\":\"newName\",\"size\":\"Godzilla\", \"price\":111.222}");
//parse
    QByteArray json = query.toUtf8();
    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse (json, &ok).toMap();
    if (ok)
    {
        QHash<int, QByteArray> roleNames = item->roleNames();
        QHash<int, QByteArray>::iterator iter;
        for (iter = roleNames.begin(); iter != roleNames.end(); ++iter)
        {
            if (result.value(iter.value()).isValid())
                item->setData(iter.key(), result.value(iter.value()));
            else
                cout<<"no data"<<endl;
 
            cout<<(int)(iter.key())<<"&"<<iter.value().data()<<endl;
            cout<<(result.value(iter.value())).toString().toUtf8().data()<<endl;
        }
    }
    else
        Q_ASSERT("An error occurred during parsing");

>对于list的数据: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
QString query("[ {\"id\":\"Banana\", \"name\":\"111\",\"size\":\"Godzilla\", \"price\":111.222}, {\"id\": \"Grape\", \"name\":222,\"size\":\"GodzillA\", \"price\":33333} ]"); //
//parse
    QVariant data = parser.parse (json, &ok);
    if (ok)
    {
        QVariantList list = data.toList();
        for (int i = 0; i < list.size(); i++)
        {
            QVariantMap listData = list.at(i).toMap();
            ListItem* item = GetListModel()->find(listData["id"].toString());
            if (item != NULL)
                //...
        }
}

Other

QML&JSON http://qt-project.org/forums/viewthread/2057

Qt使用JSON: http://stackoverflow.com/questions/4169988/easiest-way-to-parse-json-in-qt-4-7

Lighter version: qt-jsonhttps://github.com/ereilin/qt-json (需要将文件加入Project)

http://www.developer.nokia.com/Community/Wiki/%E5%9C%A8Qt%E4%B8%AD%E5%A6%82%E4%BD%95%E9%80%9A%E8%BF%87QJson_%E8%A7%A3%E6%9E%90json%E6%95%B0%E6%8D%AE

---End---


XML

XML(eXtensible Markup Language) 可扩展标记语言;

Qt中读取XML数据的方式好像有不少, 测试了一个节点方式的:

QDomDocument 代表一个XML文件, 一个文件树的root节点;  setContent()把XML文档从字节数组转化成内容设给DOMDoc.

QDomNode DOM Tree的基类; QDomElement 代表DOM tree上的一个元素;

XML: Dictionary.xml

1
2
3
4
5
6
7
<?xml version="1.0" encoding="Unicode-1-1-utf-8"?>
<strings>
<localeName>English_United_States</localeName>
<string id="101" text="Phone"/>
<string id="100" text="Name"/>
<string id="99" text="Address"/>
</strings>

Function: XMLParse

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
typedef QMap <int, QString> MY_MAP;
bool XMLparse(QString& locName, MY_MAP& map)
{
    QDomDocument doc;
    QFile file("R:\\Projects\\Data.xml");
    if (!file.open(QIODevice::ReadOnly))
        return false;
    if (!doc.setContent(&file)) {
        file.close();
        return false;
    }
    file.close();
 
    QDomElement docElem = doc.documentElement();
    QDomNode n = docElem.firstChild();
    if (n.isNull())
        return false;
 
    while(!n.isNull()) {
        QDomElement e = n.toElement();
        if(!e.isNull()) {
            if (e.tagName().compare("localeName") == 0)
                locName = e.text();
 
            if (e.tagName().compare("string") == 0)
            {
                bool ok;
                int id = e.attribute("id").toInt(&ok);
                Q_ASSERT(ok);
                if (!map.contains(id))
                    map.insert(id, e.attribute("text"));
                //qDebug() << qPrintable(e.attribute("id"));
                //qDebug() << qPrintable(e.attribute("text"));
            }
        }
        n = n.nextSibling();
    }
 
    return true;
}

Usage:

1
2
3
QString locName;
PHRASE_MAP map;
bool res = XMLparse(locName, map);

---End---

作者:RoyMuste 发表于2013-7-4 11:03:11 原文链接
阅读:22 评论:0 查看评论

原创粉丝点击