From baaae99a03202641ae5b8024e57b691fe61a6688 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Fri, 5 May 2017 16:31:03 -0700 Subject: [core, android] Factor JSON string conversions This adds a `convertJSON` template, to be used like: Error error optional foo = convertJSON(string, error); Internally, it parses the string with RapidJSON and then calls `convert(parsed, error)`. While here, rationalize GeoJSON converters and fix error handling for Tileset conversion in OfflineDownload. --- src/mbgl/style/conversion/geojson.cpp | 31 ++++++++++++------------------- src/mbgl/style/conversion/json.hpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 19 deletions(-) create mode 100644 src/mbgl/style/conversion/json.hpp (limited to 'src/mbgl/style/conversion') diff --git a/src/mbgl/style/conversion/geojson.cpp b/src/mbgl/style/conversion/geojson.cpp index 0fba6e5b4d..8103e9014a 100644 --- a/src/mbgl/style/conversion/geojson.cpp +++ b/src/mbgl/style/conversion/geojson.cpp @@ -1,33 +1,26 @@ #include - +#include #include -#include -#include +#include +#include namespace mbgl { namespace style { namespace conversion { -template <> -optional convertGeoJSON(const std::string& string, Error& error) { - rapidjson::GenericDocument, rapidjson::CrtAllocator> d; - d.Parse(string.c_str()); - - if (d.HasParseError()) { - std::stringstream message; - message << d.GetErrorOffset() << " - " << rapidjson::GetParseError_En(d.GetParseError()); - error = { message.str() }; - return {}; - } +optional Converter::operator()(const std::string& value, Error& error) const { + return convertJSON(value, error); +} - optional geoJSON = conversion::convertGeoJSON(d, error); - if (!geoJSON) { - error = { error.message }; +template <> +optional Converter::operator()(const JSValue& value, Error& error) const { + try { + return mapbox::geojson::convert(value); + } catch (const std::exception& ex) { + error = { ex.what() }; return {}; } - - return geoJSON; } } // namespace conversion diff --git a/src/mbgl/style/conversion/json.hpp b/src/mbgl/style/conversion/json.hpp new file mode 100644 index 0000000000..0817ac09df --- /dev/null +++ b/src/mbgl/style/conversion/json.hpp @@ -0,0 +1,28 @@ +#include +#include + +#include +#include + +namespace mbgl { +namespace style { +namespace conversion { + +template +optional convertJSON(const std::string& json, Error& error, Args&&...args) { + JSDocument document; + document.Parse<0>(json.c_str()); + + if (document.HasParseError()) { + std::stringstream message; + message << document.GetErrorOffset() << " - " << rapidjson::GetParseError_En(document.GetParseError()); + error = { message.str() }; + return {}; + } + + return convert(document, error, std::forward(args)...); +} + +} // namespace conversion +} // namespace style +} // namespace mbgl -- cgit v1.2.1