QJson - a Qt based library for mapping JSON data to QVariant objects

QJson home page

- Main Page
- Related Pages
- Namespaces
- Classes
- Files

- File List

qobjecthelper.cpp
1 /* This file is part of qjson
2 *
3 * Copyright (C) 2009 Till Adam <adam@kde.org>
4 * Copyright (C) 2009 Flavio Castelli <flavio@castelli.name>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License version 2.1, as published by the Free Software Foundation.
9 *
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 */
21
22
23 #include "qobjecthelper.h"
24
25 #include <QtCore/QMetaObject>
26 #include <QtCore/QMetaProperty>
27 #include <QtCore/QObject>
28
29 using namespace QJson;
30
31 class QObjectHelper::QObjectHelperPrivate {
32 };
33
34 QObjectHelper::QObjectHelper()
35 : d (new QObjectHelperPrivate)
36 {
37 }
38
39 QObjectHelper::~QObjectHelper()
40 {
41 delete d;
42 }
43
44 QVariantMap QObjectHelper::qobject2qvariant( const QObject* object,
45 const QStringList& ignoredProperties)
46 {
47 QVariantMap result;
48 const QMetaObject *metaobject = object->metaObject();
49 int count = metaobject->propertyCount();
50 for (int i=0; i<count; ++i) {
51 QMetaProperty metaproperty = metaobject->property(i);
52 const char *name = metaproperty.name();
53
54 if (ignoredProperties.contains(QLatin1String(name)) || (!metaproperty.isReadable()))
55 continue;
56
57 QVariant value = object->property(name);
58 result[QLatin1String(name)] = value;
59 }
60 return result;
61 }
62
63 void QObjectHelper::qvariant2qobject(const QVariantMap& variant, QObject* object)
64 {
65 const QMetaObject *metaobject = object->metaObject();
66
67 QVariantMap::const_iterator iter;
68 for (iter = variant.constBegin(); iter != variant.constEnd(); ++iter) {
69 int pIdx = metaobject->indexOfProperty( iter.key().toAscii() );
70
71 if ( pIdx < 0 ) {
72 continue;
73 }
74
75 QMetaProperty metaproperty = metaobject->property( pIdx );
76 QVariant::Type type = metaproperty.type();
77 QVariant v( iter.value() );
78 if ( v.canConvert( type ) ) {
79 v.convert( type );
80 metaproperty.write( object, v );
81 } else if (QString(QLatin1String("QVariant")).compare(QLatin1String(metaproperty.typeName())) == 0) {
82 metaproperty.write( object, v );
83 }
84 }
85 }
QJson
Definition: json_parser.hh:66

| hosts this site. |  | Send comments to: QJson Developers