30 #include <QJsonDocument> 32 #include <nlohmann/json.hpp> 35 : mPrecision( precision )
36 , mLayer( vectorLayer )
40 mCrs = vectorLayer->
crs();
51 mCrs = vectorLayer->
crs();
73 const QVariant &
id,
int indent )
const 82 {
"type",
"Feature" },
87 auto intId =
id.toLongLong( &ok );
90 featureJson[
"id"] = intId;
94 featureJson[
"id"] =
id.toString().toStdString();
99 featureJson[
"id"] = feature.
id();
103 if ( !geom.
isNull() && mIncludeGeometry )
110 if ( transformed.
transform( mTransform ) == 0 )
122 featureJson[
"bbox" ] = { {
130 featureJson[
"geometry" ] = geom.
asJsonObject( mPrecision );
134 featureJson[
"geometry" ] =
nullptr;
138 int attributeCounter { 0 };
140 if ( mIncludeAttributes || !extraProperties.isEmpty() )
143 if ( mIncludeAttributes )
147 QStringList formattersWhiteList;
148 formattersWhiteList << QStringLiteral(
"KeyValue" )
149 << QStringLiteral(
"List" )
150 << QStringLiteral(
"ValueRelation" )
151 << QStringLiteral(
"ValueMap" );
153 for (
int i = 0; i < fields.
count(); ++i )
155 if ( ( !mAttributeIndexes.isEmpty() && !mAttributeIndexes.contains( i ) ) || mExcludedAttributeIndexes.contains( i ) )
164 if ( formattersWhiteList.contains( fieldFormatter->
id() ) )
168 QString name = fields.
at( i ).
name();
169 if ( mAttributeDisplayName )
171 name = mLayer->attributeDisplayName( i );
178 if ( !extraProperties.isEmpty() )
180 QVariantMap::const_iterator it = extraProperties.constBegin();
181 for ( ; it != extraProperties.constEnd(); ++it )
189 if ( mLayer && mIncludeRelatedAttributes )
192 for (
const auto &relation : qgis::as_const( relations ) )
197 json relatedFeatureAttributes;
201 QVector<QVariant> attributeWidgetCaches;
204 for (
const QgsField &field : fields )
208 attributeWidgetCaches.append( fieldFormatter->
createCache( childLayer, fieldIndex, setup.
config() ) );
217 properties[ relation.name().toStdString() ] = relatedFeatureAttributes;
222 featureJson[
"properties" ] = properties;
230 {
"type",
"FeatureCollection" },
231 {
"features", json::array() }
233 const auto constFeatures = features;
234 for (
const QgsFeature &feature : constFeatures )
238 return QString::fromStdString( data.dump( indent ) );
257 if ( value.isNull() )
258 return QStringLiteral(
"null" );
260 switch ( value.type() )
264 case QVariant::LongLong:
265 case QVariant::ULongLong:
266 case QVariant::Double:
267 return value.toString();
270 return value.toBool() ?
"true" :
"false";
272 case QVariant::StringList:
275 return QString::fromUtf8( QJsonDocument::fromVariant( value ).toJson( QJsonDocument::Compact ) );
278 case QVariant::String:
279 QString v = value.toString()
280 .replace(
'\\', QLatin1String(
"\\\\" ) )
281 .replace(
'"', QLatin1String(
"\\\"" ) )
282 .replace(
'\r', QLatin1String(
"\\r" ) )
283 .replace(
'\b', QLatin1String(
"\\b" ) )
284 .replace(
'\t', QLatin1String(
"\\t" ) )
285 .replace(
'/', QLatin1String(
"\\/" ) )
286 .replace(
'\n', QLatin1String(
"\\n" ) );
288 return v.prepend(
'"' ).append(
'"' );
296 for (
int i = 0; i < fields.
count(); ++i )
299 attrs += QLatin1String(
",\n" );
308 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
311 attrs += encodeValue( fields.
at( i ).
name() ) +
':' + encodeValue( val );
313 return attrs.prepend(
'{' ).append(
'}' );
318 QString errorMessage;
322 const auto jObj(
json::parse( json.toStdString() ) );
323 if ( ! jObj.is_array() )
325 throw json::parse_error::create( 0, 0, QStringLiteral(
"JSON value must be an array" ).toStdString() );
327 for (
const auto &item : jObj )
331 if ( item.is_number_integer() )
335 else if ( item.is_number_unsigned() )
337 v = item.get<
unsigned>();
339 else if ( item.is_number_float() )
342 v = item.get<
double>();
344 else if ( item.is_string() )
346 v = QString::fromStdString( item.get<std::string>() );
348 else if ( item.is_boolean() )
350 v = item.get<
bool>();
352 else if ( item.is_null() )
355 v = QVariant( type == QVariant::Type::Invalid ? QVariant::Type::Int : type );
359 if ( type != QVariant::Invalid )
361 if ( ! v.convert( static_cast<int>( type ) ) )
363 QgsLogger::warning( QStringLiteral(
"Cannot convert json array element to specified type, ignoring: %1" ).arg( v.toString() ) );
367 result.push_back( v );
372 result.push_back( v );
376 catch ( json::parse_error &ex )
378 errorMessage = ex.what();
387 if ( val.isNull() || ! val.isValid() )
392 if ( val.type() == QVariant::Type::Map )
394 const auto vMap { val.toMap() };
395 auto jMap { json::object() };
396 for (
auto it = vMap.constBegin(); it != vMap.constEnd(); it++ )
398 jMap[ it.key().toStdString() ] = jsonFromVariant( it.value() );
402 else if ( val.type() == QVariant::Type::List )
404 const auto vList{ val.toList() };
405 auto jList { json::array() };
406 for (
const auto &v : vList )
408 jList.push_back( jsonFromVariant( v ) );
414 switch ( val.userType() )
417 case QMetaType::UInt:
418 case QMetaType::LongLong:
419 case QMetaType::ULongLong:
420 j = val.toLongLong();
422 case QMetaType::Double:
423 case QMetaType::Float:
426 case QMetaType::Bool:
430 j = val.toString().toStdString();
439 std::function<QVariant( json )> _parser { [ & ](
json jObj ) -> QVariant {
441 QString errorMessage;
442 if ( jObj.is_array() )
444 QVariantList results;
445 for (
const auto &item : jObj )
447 results.push_back( _parser( item ) );
451 else if ( jObj.is_object() )
454 for (
const auto &item : jObj.items() )
456 const auto key { QString::fromStdString( item.key() ) };
457 const auto value { _parser( item.value() ) };
458 results[ key ] = value;
464 if ( jObj.is_number_integer() )
466 result = jObj.get<
int>();
468 else if ( jObj.is_number_unsigned() )
470 result = jObj.get<
unsigned>();
472 else if ( jObj.is_boolean() )
474 result = jObj.get<
bool>();
476 else if ( jObj.is_number_float() )
479 result = jObj.get<
double>();
481 else if ( jObj.is_string() )
483 result = QString::fromStdString( jObj.get<std::string>() );
485 else if ( jObj.is_null() )
499 catch ( json::parse_error &ex )
501 QgsLogger::warning( QStringLiteral(
"Cannot parse json (%1): %2" ).arg( QString::fromStdString( ex.what() ),
502 QString::fromStdString( jsonString ) ) );
509 return parseJson( jsonString.toStdString() );
516 for (
int i = 0; i < fields.
count(); ++i )
525 val = fieldFormatter->
representValue( layer, i, setup.
config(), attributeWidgetCaches.count() >= i ? attributeWidgetCaches.at( i ) : QVariant(), val );
527 attrs[fields.
at( i ).
name().toStdString()] = jsonFromVariant( val );
Wrapper for iterator of features from vector data provider or vector layer.
A rectangle specified with double values.
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Gets the registry of available field formatters.
static json jsonFromVariant(const QVariant &v)
Converts a QVariant v to a json object.
json exportFeatureToJsonObject(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant()) const
Returns a QJsonObject representation of a feature.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source CRS for feature geometries.
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
void setVectorLayer(QgsVectorLayer *vectorLayer)
Sets the associated vector layer (required for related attribute export).
QList< QgsFeature > QgsFeatureList
QgsWkbTypes::Type wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
static void warning(const QString &msg)
Goes to qWarning.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs)
Sets the source CRS for feature geometries.
QString exportFeature(const QgsFeature &feature, const QVariantMap &extraProperties=QVariantMap(), const QVariant &id=QVariant(), int indent=-1) const
Returns a GeoJSON string representation of a feature.
Container of fields for a vector layer.
A geometry is the spatial representation of a feature.
QgsEditorWidgetSetup editorWidgetSetup() const
Gets the editor widget setup for the field.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
const QgsCoordinateReferenceSystem & crs
int count() const
Returns number of items.
QgsVectorLayer * vectorLayer() const
Returns the associated vector layer, if set.
QString exportFeatures(const QgsFeatureList &features, int indent=-1) const
Returns a GeoJSON string representation of a list of features (feature collection).
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields, QTextCodec *encoding)
Attempts to parse a string representing a collection of features using OGR.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
static QString encodeValue(const QVariant &value)
Encodes a value to a JSON string representation, adding appropriate quotations and escaping where req...
static QgsFields stringToFields(const QString &string, QTextCodec *encoding)
Attempts to retrieve the fields from a GeoJSON string representing a collection of features...
This class wraps a request for features to a vector layer (or directly its vector data provider)...
QList< QgsRelation > referencedRelations(QgsVectorLayer *layer=nullptr) const
Gets all relations where this layer is the referenced part (i.e.
static QgsFields stringToFields(const QString &string, QTextCodec *encoding)
Attempts to retrieve the fields from a string representing a collection of features using OGR...
Encapsulate a field in an attribute table or data source.
QgsRelationManager relationManager
static QgsFeatureList stringToFeatureList(const QString &string, const QgsFields &fields, QTextCodec *encoding)
Attempts to parse a GeoJSON string to a collection of features.
static json exportAttributesToJsonObject(const QgsFeature &feature, QgsVectorLayer *layer=nullptr, const QVector< QVariant > &attributeWidgetCaches=QVector< QVariant >())
Exports all attributes from a QgsFeature as a json object.
static QString exportAttributes(const QgsFeature &feature, QgsVectorLayer *layer=nullptr, const QVector< QVariant > &attributeWidgetCaches=QVector< QVariant >())
Exports all attributes from a QgsFeature as a JSON map type.
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
QgsJsonExporter(QgsVectorLayer *vectorLayer=nullptr, int precision=6)
Constructor for QgsJsonExporter.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
virtual json asJsonObject(int precision=17) const
Exports the geometry to a json object.
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
This class represents a coordinate reference system (CRS).
static QVariantList parseArray(const QString &json, QVariant::Type type=QVariant::Invalid)
Parse a simple array (depth=1)
double xMinimum() const
Returns the x minimum value (left side of rectangle).
double yMaximum() const
Returns the y maximum value (top side of rectangle).
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
static QVariant parseJson(const std::string &jsonString)
Converts JSON jsonString to a QVariant, in case of parsing error an invalid QVariant is returned...
Custom exception class for Coordinate Reference System related exceptions.
bool nextFeature(QgsFeature &f)
Geometry is not required. It may still be returned if e.g. required for a filter condition.
QgsSQLStatement::Node * parse(const QString &str, QString &parserErrorMsg)
Represents a vector layer which manages a vector based data sets.
static Type flatType(Type type)
Returns the flat type for a WKB type.
QgsCoordinateReferenceSystem crs
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.