1/****************************************************************************
2**
3** Copyright (C) 2018 Intel Corporation.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include "jsonconverter.h"
52
53#include <QFile>
54#include <QJsonArray>
55#include <QJsonDocument>
56#include <QJsonObject>
57#include <QJsonValue>
58
59static JsonConverter jsonConverter;
60
61static const char optionHelp[] =
62 "compact=no|yes Use compact JSON form.\n";
63
64static QJsonDocument convertFromVariant(const QVariant &v)
65{
66 QJsonDocument doc = QJsonDocument::fromVariant(variant: v);
67 if (!doc.isObject() && !doc.isArray()) {
68 fprintf(stderr, format: "Could not convert contents to JSON.\n");
69 exit(EXIT_FAILURE);
70 }
71 return doc;
72}
73
74JsonConverter::JsonConverter()
75{
76}
77
78QString JsonConverter::name()
79{
80 return "json";
81}
82
83Converter::Direction JsonConverter::directions()
84{
85 return InOut;
86}
87
88Converter::Options JsonConverter::outputOptions()
89{
90 return {};
91}
92
93const char *JsonConverter::optionsHelp()
94{
95 return optionHelp;
96}
97
98bool JsonConverter::probeFile(QIODevice *f)
99{
100 if (QFile *file = qobject_cast<QFile *>(object: f)) {
101 if (file->fileName().endsWith(s: QLatin1String(".json")))
102 return true;
103 }
104
105 if (f->isReadable()) {
106 QByteArray ba = f->peek(maxlen: 1);
107 return ba == "{" || ba == "[";
108 }
109 return false;
110}
111
112QVariant JsonConverter::loadFile(QIODevice *f, Converter *&outputConverter)
113{
114 if (!outputConverter)
115 outputConverter = this;
116
117 QJsonParseError error;
118 QJsonDocument doc;
119 if (auto file = qobject_cast<QFile *>(object: f)) {
120 const char *ptr = reinterpret_cast<char *>(file->map(offset: 0, size: file->size()));
121 if (ptr)
122 doc = QJsonDocument::fromJson(json: QByteArray::fromRawData(ptr, size: file->size()), error: &error);
123 }
124
125 if (doc.isNull())
126 doc = QJsonDocument::fromJson(json: f->readAll(), error: &error);
127 if (error.error) {
128 fprintf(stderr, format: "Could not parse JSON content: offset %d: %s",
129 error.offset, qPrintable(error.errorString()));
130 exit(EXIT_FAILURE);
131 }
132 if (outputConverter == null)
133 return QVariant();
134 return doc.toVariant();
135}
136
137void JsonConverter::saveFile(QIODevice *f, const QVariant &contents, const QStringList &options)
138{
139 QJsonDocument::JsonFormat format = QJsonDocument::Indented;
140 for (const QString &s : options) {
141 if (s == QLatin1String("compact=no")) {
142 format = QJsonDocument::Indented;
143 } else if (s == QLatin1String("compact=yes")) {
144 format = QJsonDocument::Compact;
145 } else {
146 fprintf(stderr, format: "Unknown option '%s' to JSON output. Valid options are:\n%s", qPrintable(s), optionHelp);
147 exit(EXIT_FAILURE);
148 }
149 }
150
151 f->write(data: convertFromVariant(v: contents).toJson(format));
152}
153

source code of qtbase/examples/corelib/serialization/convert/jsonconverter.cpp