ECSTASY
All in the name
Loading...
Searching...
No Matches
ecstasy::serialization::JsonSerializer Class Reference

JsonSerializer class. More...

#include <JsonSerializer.hpp>

Inheritance diagram for ecstasy::serialization::JsonSerializer:
Collaboration diagram for ecstasy::serialization::JsonSerializer:

Public Types

enum class  NestedContextOp { NewObject , NewArray , Close }
 Nested context operations, used to open and close nested objects and arrays in streams easily. More...
 

Public Member Functions

 JsonSerializer ()
 Construct a new Raw Serializer instance.
 
 JsonSerializer (const std::string &content)
 Construct a new Raw Serializer and import the content from a string.
 
 JsonSerializer (const std::filesystem::path &filename)
 Construct a new Raw Serializer and import the content from a file.
 
 JsonSerializer (std::istream &stream)
 Construct a new Raw Serializer and import the content from a stream.
 
 ~JsonSerializer () override=default
 Destroy the JsonSerializer.
 
void clear () override final
 Clear the serializer content.
 
size_t size () const override final
 Get the size of the serializer content (in bytes).
 
void importStream (std::istream &stream) override final
 Import data from a stream into the serializer.
 
void exportStream (std::ostream &stream) const override final
 Export the serializer content to a stream.
 
void resetCursor ()
 Reset the json read/write cursor to the begining of the document.
 
template<typename T , typename = typename std::enable_if< (std::is_same_v<T, std::string> || std::is_same_v<T, std::string_view>) || std::is_bounded_array_v<T> || util::meta::is_std_vector<T>::value || std::is_fundamental_v<T> || std::is_same_v<T, std::type_info> || std::is_same_v<T, NestedContextOp> , int>::type>
JsonSerializersaveImpl (const T &object)
 Save an object to the serializer.
 
template<typename U >
requires std::is_same_v<U, NestedContextOp>
JsonSerializerupdateImpl (const U &object)
 Update an existing object from the serializer.
 
template<typename U , typename = typename std::enable_if<( std::is_same_v<U, std::string> || std::is_same_v<U, std::string_view> || std::is_bounded_array_v<U> || util::meta::is_std_vector<U>::value) , int>::type>
JsonSerializerupdateImpl (U &object)
 Update an existing object from the serializer.
 
template<typename U >
requires std::is_fundamental_v<U> || std::is_same_v<U, std::string>
loadImpl ()
 Load an object from the serializer.
 
rapidjson::ValuereadCurrentValue (bool andMoveCursor=true)
 Access the current value in the json document, and move the cursor to the next value.
 
JsonSerializernewNested (rapidjson::Type type, bool create=true)
 Open a new nested object or array context in the current object (see getWriteCursor).
 
JsonSerializernewNestedObject (bool create=true)
 Wrapper for JsonSerializer::newNested() with rapidjson::kObjectType as parameter.
 
JsonSerializernewNestedArray (bool create=true)
 Wrapper for JsonSerializer::newNested() with rapidjson::kArrayType as parameter.
 
JsonSerializercloseNested ()
 Close the current nested object or array opened with newNestedObject or newNestedArray (or newNested).
 
rapidjson::ValuegetWriteCursor () noexcept
 Get a reference to the current cursor (ie nested objects or arrays).
 
JsonSerializeraddValue (rapidjson::Value &&value)
 Add a value to the current object or array.
 
bool isArrayEnd ()
 Check if the current cursor is at the end of an array.
 
size_t getArraySize ()
 Get the size of the current array.
 
- Public Member Functions inherited from ecstasy::serialization::Serializer< JsonSerializer >
 Serializer ()=default
 Construct a new Serializer.
 
 ~Serializer () override=default
 Destroy the Serializer.
 
constexpr JsonSerializerinner ()
 Get a reference to the inner serializer.
 
void importFile (const std::filesystem::path &filename) override
 Import data from a file into the serializer.
 
void importBytes (const std::string &content) override
 Import data from a string into the serializer.
 
void exportFile (const std::filesystem::path &filename) const override
 Export the serializer content to a file.
 
std::string exportBytes () const override
 Export the serializer content to a string.
 
JsonSerializersave (const U &object)
 Save an object to the serializer.
 
JsonSerializersaveEntityComponent (const C &component)
 Save an entity component to the serializer.
 
JsonSerializersaveEntity (const RegistryEntity &entity)
 Save an entity to the serializer with explicit components.
 
JsonSerializersaveEntity (RegistryEntity &entity)
 Save all registered components of an entity to the serializer.
 
load ()
 Load an object from the serializer.
 
RegistryEntity loadEntity (Registry &registry)
 Load an entity component from the serializer.
 
JsonSerializerupdate (U &object)
 Update an existing object from the serializer.
 
JsonSerializerupdateEntity (RegistryEntity &entity)
 Update all registered components of an entity from the serializer.
 
JsonSerializeroperator<< (const U &object)
 Operator overload to simplify the save method.
 
JsonSerializeroperator>> (U &object)
 Operator overload to simplify the update method.
 
- Public Member Functions inherited from ecstasy::serialization::ISerializer
virtual ~ISerializer ()=default
 Destroy the ISerializer.
 
virtual void clear ()=0
 Clear the serializer content.
 
virtual size_t size () const =0
 Get the size of the serializer content (in bytes).
 
virtual void importFile (const std::filesystem::path &filename)=0
 Import data from a file into the serializer.
 
virtual void importBytes (const std::string &content)=0
 Import data from a string into the serializer.
 
virtual void importStream (std::istream &stream)=0
 Import data from a stream into the serializer.
 
virtual void exportFile (const std::filesystem::path &filename) const =0
 Export the serializer content to a file.
 
virtual std::string exportBytes () const =0
 Export the serializer content to a string.
 
virtual void exportStream (std::ostream &stream) const =0
 Export the serializer content to a stream.
 

Static Public Attributes

static constexpr NestedContextOp NewObject = NestedContextOp::NewObject
 Open a new object (Creating it in save mode)
 
static constexpr NestedContextOp NewArray = NestedContextOp::NewArray
 Open a new array (Creating it in save mode)
 
static constexpr NestedContextOp Close = NestedContextOp::Close
 Close the current object or array.
 
- Static Public Attributes inherited from ecstasy::serialization::Serializer< JsonSerializer >
static constexpr bool is_constructible
 Check if a type is constructible from the serializer.
 

Private Member Functions

OptionalEntityComponentSerializer loadComponentSerializer () override final
 Load the next component serializer from the stream.
 
void beforeSaveEntity (RegistryEntity &entity) override final
 Optional method triggered at the start of saveEntity.
 
void afterSaveEntity (RegistryEntity &entity) override final
 Optional method triggered at the end of saveEntity.
 
void beforeUpdateEntity (RegistryEntity &entity) override final
 Optional method triggered at the start of updateEntity.
 
void afterUpdateEntity (RegistryEntity &entity) override final
 Optional method triggered at the end of updateEntity.
 

Private Attributes

rapidjson::Document _document
 RapidJson document.
 
std::stack< std::reference_wrapper< rapidjson::Value > > _stack
 Stack of nested objects or arrays, to keep track of the current context.
 
std::stack< rapidjson::Value::ValueIterator_arrayIterators
 Stack of array iterators, to keep track of the current array element.
 
std::stack< rapidjson::Value::MemberIterator_objectIterators
 Stack of object iterators, to keep track of the current object element.
 
std::string _nextKey
 Next key to use for the next object value.
 

Additional Inherited Members

- Static Public Member Functions inherited from ecstasy::serialization::Serializer< JsonSerializer >
static IEntityComponentSerializerregisterComponent (std::string_view name)
 Register a component to this serializer type.
 
static bool hasEntityComponentSerializer ()
 Get the registered components of the serializer.
 
- Protected Types inherited from ecstasy::serialization::Serializer< JsonSerializer >
using Parent = Serializer< JsonSerializer >
 Parent serializer type, used for inheriting classes.
 
using OptionalEntityComponentSerializer = std::optional< std::reference_wrapper< IEntityComponentSerializer > >
 
virtual OptionalEntityComponentSerializer loadComponentSerializer ()=0
 Load the next component serializer from the stream.
 
virtual void beforeSaveEntity (RegistryEntity &entity)
 Optional method triggered at the start of saveEntity.
 
virtual void afterSaveEntity (RegistryEntity &entity)
 Optional method triggered at the end of saveEntity.
 
virtual void beforeUpdateEntity (RegistryEntity &entity)
 Optional method triggered at the start of updateEntity.
 
virtual void afterUpdateEntity (RegistryEntity &entity)
 Optional method triggered at the end of updateEntity.
 

Detailed Description

JsonSerializer class.

Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-04-30)

Definition at line 38 of file JsonSerializer.hpp.

Member Enumeration Documentation

◆ NestedContextOp

Nested context operations, used to open and close nested objects and arrays in streams easily.

Note
Use the static constexpr instances to use them in stream operations.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-10)
Enumerator
NewObject 

Open a new object (Creating it in save mode)

NewArray 

Open a new array (Creating it in save mode)

Close 

Close the current object or array.

Definition at line 48 of file JsonSerializer.hpp.

48 {
49 NewObject,
50 NewArray,
51 Close
52 };
static constexpr NestedContextOp Close
Close the current object or array.
static constexpr NestedContextOp NewArray
Open a new array (Creating it in save mode)
static constexpr NestedContextOp NewObject
Open a new object (Creating it in save mode)

Constructor & Destructor Documentation

◆ JsonSerializer() [1/4]

ecstasy::serialization::JsonSerializer::JsonSerializer ( )
inline

Construct a new Raw Serializer instance.

Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-04-30)

Definition at line 66 of file JsonSerializer.hpp.

67 {
69 };
rapidjson::Document _document
RapidJson document.
GenericValue & SetArray()

◆ JsonSerializer() [2/4]

ecstasy::serialization::JsonSerializer::JsonSerializer ( const std::string content)
inline

Construct a new Raw Serializer and import the content from a string.

Parameters
[in]contentString to import.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-09-12)

Definition at line 79 of file JsonSerializer.hpp.

80 {
81 importBytes(content);
82 }
void importBytes(const std::string &content) override
Import data from a string into the serializer.

◆ JsonSerializer() [3/4]

ecstasy::serialization::JsonSerializer::JsonSerializer ( const std::filesystem::path filename)
inlineexplicit

Construct a new Raw Serializer and import the content from a file.

Parameters
[in]filenamePath to the file to import.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-09-12)

Definition at line 92 of file JsonSerializer.hpp.

93 {
94 importFile(filename);
95 }
void importFile(const std::filesystem::path &filename) override
Import data from a file into the serializer.

◆ JsonSerializer() [4/4]

ecstasy::serialization::JsonSerializer::JsonSerializer ( std::istream stream)
inline

Construct a new Raw Serializer and import the content from a stream.

Parameters
[in]streamInput stream.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-09-12)

Definition at line 104 of file JsonSerializer.hpp.

105 {
106 importStream(stream);
107 }
void importStream(std::istream &stream) override final
Import data from a stream into the serializer.

◆ ~JsonSerializer()

ecstasy::serialization::JsonSerializer::~JsonSerializer ( )
overridedefault

Destroy the JsonSerializer.

Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-06-11)

Member Function Documentation

◆ addValue()

JsonSerializer & ecstasy::serialization::JsonSerializer::addValue ( rapidjson::Value &&  value)
inline

Add a value to the current object or array.

If the current object is an array, the value will be appended to it. If the current object is an object, the first call will set the key (string) for the next value, and the second call will add the value to the object (using the previous key identifier).

Parameters
[in]valueValue to add.
Returns
JsonSerializer& Reference to this for chain calls.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-10)

Definition at line 480 of file JsonSerializer.hpp.

481 {
483
484 if (cursor.IsObject()) {
485 if (_nextKey.empty()) {
486 if (value.IsString())
487 _nextKey = value.GetString();
488 else
489 throw std::logic_error("Json object key is missing.");
490 } else {
491 cursor.AddMember(
493 _nextKey.clear();
494 }
495 } else {
496 cursor.PushBack(value, _document.GetAllocator());
497 }
498 return *this;
499 }
T c_str(T... args)
std::string _nextKey
Next key to use for the next object value.
rapidjson::Value & getWriteCursor() noexcept
Get a reference to the current cursor (ie nested objects or arrays).
GenericValue & PushBack(GenericValue &value, Allocator &allocator)
GenericValue & AddMember(GenericValue &name, GenericValue &value, Allocator &allocator)
T clear(T... args)
T empty(T... args)

◆ afterSaveEntity()

void ecstasy::serialization::JsonSerializer::afterSaveEntity ( RegistryEntity entity)
inlinefinaloverrideprivatevirtual

Optional method triggered at the end of saveEntity.

Parameters
[in]entityEntity being saved.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-11)

Reimplemented from ecstasy::serialization::Serializer< JsonSerializer >.

Definition at line 577 of file JsonSerializer.hpp.

578 {
579 closeNested();
580 }
JsonSerializer & closeNested()
Close the current nested object or array opened with newNestedObject or newNestedArray (or newNested)...

◆ afterUpdateEntity()

void ecstasy::serialization::JsonSerializer::afterUpdateEntity ( RegistryEntity entity)
inlinefinaloverrideprivatevirtual

Optional method triggered at the end of updateEntity.

Parameters
[in]entityEntity being updated.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-11)

Reimplemented from ecstasy::serialization::Serializer< JsonSerializer >.

Definition at line 590 of file JsonSerializer.hpp.

591 {
592 _objectIterators.pop();
593 closeNested();
594 }
std::stack< rapidjson::Value::MemberIterator > _objectIterators
Stack of object iterators, to keep track of the current object element.

◆ beforeSaveEntity()

void ecstasy::serialization::JsonSerializer::beforeSaveEntity ( RegistryEntity entity)
inlinefinaloverrideprivatevirtual

Optional method triggered at the start of saveEntity.

Parameters
[in]entityEntity being saved.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-11)

Reimplemented from ecstasy::serialization::Serializer< JsonSerializer >.

Definition at line 571 of file JsonSerializer.hpp.

572 {
574 }
JsonSerializer & newNestedObject(bool create=true)
Wrapper for JsonSerializer::newNested() with rapidjson::kObjectType as parameter.

◆ beforeUpdateEntity()

void ecstasy::serialization::JsonSerializer::beforeUpdateEntity ( RegistryEntity entity)
inlinefinaloverrideprivatevirtual

Optional method triggered at the start of updateEntity.

Parameters
[in]entityEntity being updated.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-11)

Reimplemented from ecstasy::serialization::Serializer< JsonSerializer >.

Definition at line 583 of file JsonSerializer.hpp.

584 {
585 newNestedObject(false);
586 _objectIterators.push(getWriteCursor().MemberBegin());
587 }

◆ clear()

void ecstasy::serialization::JsonSerializer::clear ( )
inlinefinaloverridevirtual

Clear the serializer content.

Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-09-12)

Implements ecstasy::serialization::ISerializer.

Definition at line 118 of file JsonSerializer.hpp.

119 {
122 }

◆ closeNested()

JsonSerializer & ecstasy::serialization::JsonSerializer::closeNested ( )
inline

Close the current nested object or array opened with newNestedObject or newNestedArray (or newNested).

Returns
JsonSerializer& Reference to this for chain calls.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-10)

Definition at line 444 of file JsonSerializer.hpp.

445 {
446 if (_stack.top().get().IsArray() && !_arrayIterators.empty())
447 _arrayIterators.pop();
448 _stack.pop();
449 return *this;
450 }
std::stack< std::reference_wrapper< rapidjson::Value > > _stack
Stack of nested objects or arrays, to keep track of the current context.
std::stack< rapidjson::Value::ValueIterator > _arrayIterators
Stack of array iterators, to keep track of the current array element.

◆ exportStream()

void ecstasy::serialization::JsonSerializer::exportStream ( std::ostream stream) const
inlinefinaloverridevirtual

Export the serializer content to a stream.

Parameters
[in]streamStream to export the serializer content to.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-09-12)

Implements ecstasy::serialization::ISerializer.

Definition at line 140 of file JsonSerializer.hpp.

141 {
142 rapidjson::OStreamWrapper osw(stream);
144
145 _document.Accept(writer);
146 }
bool Accept(Handler &handler) const

◆ getArraySize()

size_t ecstasy::serialization::JsonSerializer::getArraySize ( )
inline

Get the size of the current array.

Returns
size_t Size of the current array.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2025-04-10)

Definition at line 530 of file JsonSerializer.hpp.

531 {
533
534 if (!cursor.IsArray()) {
535 throw std::invalid_argument("Invalid cursor type. Expected object or array.");
536 }
537 return cursor.Size();
538 }
SizeType Size() const

◆ getWriteCursor()

rapidjson::Value & ecstasy::serialization::JsonSerializer::getWriteCursor ( )
inlinenoexcept

Get a reference to the current cursor (ie nested objects or arrays).

Returns
rapidjson::Value& Reference to the current cursor.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-10)

Definition at line 460 of file JsonSerializer.hpp.

461 {
462 if (_stack.empty())
463 return _document;
464 return _stack.top();
465 }

◆ importStream()

void ecstasy::serialization::JsonSerializer::importStream ( std::istream stream)
inlinefinaloverridevirtual

Import data from a stream into the serializer.

Parameters
[in]streamStream to import.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-09-12)

Implements ecstasy::serialization::ISerializer.

Definition at line 131 of file JsonSerializer.hpp.

132 {
133 rapidjson::IStreamWrapper isw(stream);
134
135 clear();
137 }
void clear() override final
Clear the serializer content.
GenericDocument & ParseStream(InputStream &is)

◆ isArrayEnd()

bool ecstasy::serialization::JsonSerializer::isArrayEnd ( )
inline

Check if the current cursor is at the end of an array.

Returns
bool True if the cursor is at the end of an array, false otherwise.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2025-04-10)

Definition at line 509 of file JsonSerializer.hpp.

510 {
512
513 if (!cursor.IsArray()) {
514 throw std::invalid_argument("Invalid cursor type. Expected object or array.");
515 }
516 // If the array is empty, push the first element (first document element)
517 if (_arrayIterators.empty())
518 _arrayIterators.push(cursor.Begin());
519 return _arrayIterators.top() == cursor.End();
520 }
ValueIterator Begin()
ValueIterator End()

◆ loadComponentSerializer()

OptionalEntityComponentSerializer ecstasy::serialization::JsonSerializer::loadComponentSerializer ( )
inlinefinaloverrideprivatevirtual

Load the next component serializer from the stream.

Note
Return std::nullopt_t if no more components are available.
Returns
OptionalEntityComponentSerializer Optional reference to the next component serializer.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-04)

Implements ecstasy::serialization::Serializer< JsonSerializer >.

Definition at line 553 of file JsonSerializer.hpp.

554 {
555 if (getWriteCursor().IsObject()) {
556 if (_objectIterators.empty())
557 throw std::logic_error(
558 "No object iterator. This function should be called in an updateEntity context.");
559 if (_objectIterators.top() == getWriteCursor().MemberEnd())
560 return std::nullopt;
561 _nextKey = _objectIterators.top()->name.GetString();
562 ++_objectIterators.top();
564 } else
566 .get(load<std::size_t>())
568 }
ecstasy::serialization::IEntityComponentSerializer & getSerializer() const noexcept
Get a reference to the entity component serializer for the given serializer type.
Definition AType.hpp:175
static TypeRegistry & getInstance() noexcept
Get the Instance object.
AType & get(const T &target) const
Get a reference to the AType instance matching the target.
JsonSerializer()
Construct a new Raw Serializer instance.

◆ loadImpl()

template<typename U >
requires std::is_fundamental_v<U> || std::is_same_v<U, std::string>
U ecstasy::serialization::JsonSerializer::loadImpl ( )
inline

Load an object from the serializer.

Note
This construct a new object and consume the associated data from the serializer.
Template Parameters
UType of the object to load.
Returns
U Loaded object.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-04-30)

Definition at line 297 of file JsonSerializer.hpp.

298 {
299 const rapidjson::Value &value = readCurrentValue(true);
300
301 // Read Boolean
302 if constexpr (std::is_same_v<U, bool>) {
303 return value.GetBool();
304 }
305 // Read Integer
306 else if constexpr (std::numeric_limits<U>::is_integer) {
307 if constexpr (std::numeric_limits<U>::is_signed) {
308 if constexpr (sizeof(U) < 8)
309 return static_cast<U>(value.GetInt());
310 else
311 return static_cast<U>(value.GetInt64());
312 } else {
313 if constexpr (sizeof(U) < 8)
314 return static_cast<U>(value.GetUint());
315 else
316 return static_cast<U>(value.GetUint64());
317 }
318 }
319 // Read Floating point
320 else if constexpr (std::is_floating_point_v<U>) {
321 if constexpr (sizeof(U) == 4)
322 return value.GetFloat();
323 else
324 return value.GetDouble();
325 }
326 // Read String
327 else if constexpr (std::is_same_v<U, std::string>) {
328 return std::string(value.GetString(), value.GetStringLength());
329 }
330 }
rapidjson::Value & readCurrentValue(bool andMoveCursor=true)
Access the current value in the json document, and move the cursor to the next value.
SizeType GetStringLength() const
float GetFloat() const
double GetDouble() const

◆ newNested()

JsonSerializer & ecstasy::serialization::JsonSerializer::newNested ( rapidjson::Type  type,
bool  create = true 
)
inline

Open a new nested object or array context in the current object (see getWriteCursor).

The context can be closed with closeNested.

Warning
If the context is an object you must set a key before adding a value to it.
Parameters
[in]typeType of the nested object or array.
[in]createIf true, create the nested object or array (for save mode).
Returns
JsonSerializer& Reference to this for chain calls.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-10)

Definition at line 387 of file JsonSerializer.hpp.

388 {
389 if (type != rapidjson::kObjectType && type != rapidjson::kArrayType)
390 throw std::invalid_argument("Invalid type for nested object.");
391
392 if (create) {
394 std::string key = _nextKey;
395
397 if (cursor.IsArray())
398 _stack.push(cursor[cursor.Size() - 1]);
399 else
400 _stack.push(cursor[key.c_str()]);
401 } else {
402 _stack.push(readCurrentValue());
403 if (getWriteCursor().IsArray())
404 _arrayIterators.push(getWriteCursor().Begin());
405 }
406 return *this;
407 }
JsonSerializer & addValue(rapidjson::Value &&value)
Add a value to the current object or array.

◆ newNestedArray()

JsonSerializer & ecstasy::serialization::JsonSerializer::newNestedArray ( bool  create = true)
inline

Wrapper for JsonSerializer::newNested() with rapidjson::kArrayType as parameter.

Returns
JsonSerializer& Reference to this for chain calls.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-10)

Definition at line 430 of file JsonSerializer.hpp.

431 {
432 return newNested(rapidjson::kArrayType, create);
433 }
JsonSerializer & newNested(rapidjson::Type type, bool create=true)
Open a new nested object or array context in the current object (see getWriteCursor).

◆ newNestedObject()

JsonSerializer & ecstasy::serialization::JsonSerializer::newNestedObject ( bool  create = true)
inline

Wrapper for JsonSerializer::newNested() with rapidjson::kObjectType as parameter.

Returns
JsonSerializer& Reference to this for chain calls.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-10)

Definition at line 417 of file JsonSerializer.hpp.

418 {
419 return newNested(rapidjson::kObjectType, create);
420 }

◆ readCurrentValue()

rapidjson::Value & ecstasy::serialization::JsonSerializer::readCurrentValue ( bool  andMoveCursor = true)
inline

Access the current value in the json document, and move the cursor to the next value.

Parameters
[in]andMoveCursorIf true, move the cursor to the next value.
Returns
rapidjson::Value& Reference to the current value.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-11)

Definition at line 342 of file JsonSerializer.hpp.

343 {
345
346 if (cursor.IsObject()) {
347 if (_nextKey.empty())
348 throw std::invalid_argument("No key set for object value.");
349 rapidjson::Value &result = cursor[_nextKey.c_str()];
350 if (andMoveCursor)
351 _nextKey.clear();
352 return result;
353 } else {
354 if (!cursor.IsArray()) {
355 throw std::invalid_argument("Invalid cursor type. Expected object or array.");
356 }
357 // If the array is empty, push the first element (first document element)
358 if (_arrayIterators.empty())
359 _arrayIterators.push(cursor.Begin());
360
361 // If we reached the end of the array, throw an exception
362 if (_arrayIterators.top() == cursor.End())
363 throw std::out_of_range("End of array reached.");
364
365 rapidjson::Value *value = _arrayIterators.top();
366 // Move the cursor to the next element
367 if (andMoveCursor)
368 ++_arrayIterators.top();
369 return *value;
370 }
371 }

◆ resetCursor()

void ecstasy::serialization::JsonSerializer::resetCursor ( )
inline

Reset the json read/write cursor to the begining of the document.

Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-10-11)

Definition at line 154 of file JsonSerializer.hpp.

155 {
156 while (!_stack.empty())
157 _stack.pop();
158 while (!_arrayIterators.empty())
159 _arrayIterators.pop();
160 }

◆ saveImpl()

template<typename T , typename = typename std::enable_if< (std::is_same_v<T, std::string> || std::is_same_v<T, std::string_view>) || std::is_bounded_array_v<T> || util::meta::is_std_vector<T>::value || std::is_fundamental_v<T> || std::is_same_v<T, std::type_info> || std::is_same_v<T, NestedContextOp> , int>::type>
JsonSerializer & ecstasy::serialization::JsonSerializer::saveImpl ( const T &  object)
inline

Save an object to the serializer.

Template Parameters
UType of the object to save.
Parameters
[in]objectObject to save.
Returns
S& Reference to this for chain calls.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-04-30)

Definition at line 174 of file JsonSerializer.hpp.

175 {
176 if constexpr (std::is_same_v<T, NestedContextOp>) {
177 switch (object) {
180 case NestedContextOp::Close: closeNested(); break;
181 }
182 } else if constexpr (std::is_same_v<T, std::string> || std::is_same_v<T, std::string_view>
183 || util::meta::is_type_bounded_array_v<T, char>) {
184 rapidjson::Value value;
185
186 if constexpr (std::is_same_v<T, std::string>)
187 value.SetString(
188 object.c_str(), static_cast<rapidjson::SizeType>(object.length()), _document.GetAllocator());
189 else if constexpr (std::is_same_v<T, std::string_view>)
190 value.SetString(
191 object.data(), static_cast<rapidjson::SizeType>(object.length()), _document.GetAllocator());
192 else
193 value.SetString(object, _document.GetAllocator());
194
195 addValue(std::move(value.Move()));
196 } else if constexpr (std::is_bounded_array_v<T>) {
198
199 for (size_t i = 0; i < std::extent_v<T>; i++)
200 array.PushBack(object[i], _document.GetAllocator());
201 addValue(std::move(array.Move()));
202 } else if constexpr (util::meta::is_std_vector<T>::value) {
204
205 for (const auto &elem : object)
206 array.PushBack(elem, _document.GetAllocator());
207 addValue(std::move(array.Move()));
208 } else if constexpr (std::is_same_v<T, std::type_info>) {
209 // Will raise an exception if the serializer is not registered
210 rtti::AType &type = rtti::TypeRegistry::getInstance().get(object);
211
212 if (getWriteCursor().IsObject()) {
213 save(type.getTypeName());
214 } else
215 save(type.getHash());
216 } else if constexpr (std::is_fundamental_v<T>) {
217 addValue(rapidjson::Value(object));
218 } else {
219 return Parent::save(object);
220 }
221 return *this;
222 }
JsonSerializer & newNestedArray(bool create=true)
Wrapper for JsonSerializer::newNested() with rapidjson::kArrayType as parameter.
@ NewArray
Open a new array (Creating it in save mode)
@ NewObject
Open a new object (Creating it in save mode)
JsonSerializer & save(const U &object)
Save an object to the serializer.
GenericValue & Move() RAPIDJSON_NOEXCEPT
GenericValue & SetString(const Ch *s, SizeType length)
unsigned SizeType
Check if a type is a std::vector.

◆ size()

size_t ecstasy::serialization::JsonSerializer::size ( ) const
inlinefinaloverridevirtual

Get the size of the serializer content (in bytes).

Returns
size_t Size of the serializer content in bytes.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-09-12)

Implements ecstasy::serialization::ISerializer.

Definition at line 125 of file JsonSerializer.hpp.

126 {
127 return exportBytes().size();
128 }
std::string exportBytes() const override
Export the serializer content to a string.
T size(T... args)

◆ updateImpl() [1/2]

template<typename U >
requires std::is_same_v<U, NestedContextOp>
JsonSerializer & ecstasy::serialization::JsonSerializer::updateImpl ( const U &  object)
inline

Update an existing object from the serializer.

Note
If the object is fundamental, it will use the assignment operator, otherwise the << operator is expected to be implemented in U.
Template Parameters
UType of the object to update.
Parameters
[in]objectExisting object to update.
Returns
S& Reference to this for chain calls.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-04-30)

Definition at line 227 of file JsonSerializer.hpp.

228 {
229 switch (object) {
231 case NestedContextOp::NewArray: newNestedArray(false); break;
232 case NestedContextOp::Close: closeNested(); break;
233 }
234 return *this;
235 }

◆ updateImpl() [2/2]

template<typename U , typename = typename std::enable_if<( std::is_same_v<U, std::string> || std::is_same_v<U, std::string_view> || std::is_bounded_array_v<U> || util::meta::is_std_vector<U>::value) , int>::type>
JsonSerializer & ecstasy::serialization::JsonSerializer::updateImpl ( U &  object)
inline

Update an existing object from the serializer.

Note
If the object is fundamental, it will use the assignment operator, otherwise the << operator is expected to be implemented in U.
Template Parameters
UType of the object to update.
Parameters
[in]objectExisting object to update.
Returns
S& Reference to this for chain calls.
Author
Andréas Leroux (andre.nosp@m.as.l.nosp@m.eroux.nosp@m.@epi.nosp@m.tech..nosp@m.eu)
Since
1.0.0 (2024-04-30)

Definition at line 246 of file JsonSerializer.hpp.

247 {
248 // Handle string key for object values
249 if constexpr (std::is_same_v<U, std::string> || std::is_same_v<U, std::string_view>
250 || util::meta::is_type_bounded_array_v<U, char>) {
251 if (getWriteCursor().IsObject() && _nextKey.empty())
252 _nextKey = object;
253 else {
254 if constexpr (std::is_same_v<U, std::string>)
255 object = load<U>();
256 else
257 throw std::invalid_argument("string_view and char[] can only be used for object keys.");
258 }
259 }
260 // Handle bounded arrays
261 else if constexpr (std::is_bounded_array_v<U>) {
262 newNestedArray(false);
263
264 // Need to fetch the new cursor after the new nested array
265 if (getWriteCursor().Size() != std::extent_v<U>)
266 throw std::invalid_argument("Array size mismatch.");
267
268 for (size_t i = 0; i < std::extent_v<U>; i++)
269 update(object[i]);
270 closeNested();
271 }
272 // Handle std::vector
273 else if constexpr (util::meta::is_std_vector<U>::value) {
274 newNestedArray(false);
276
277 object.clear();
278 object.reserve(size);
279 for (size_t i = 0; i < size; i++) {
280 if constexpr (is_constructible<typename U::value_type>)
281 object.emplace_back(*this);
282 else
283 object.push_back(std::move(load<typename U::value_type>()));
284 }
285 closeNested();
286 } else
287 return Parent::update(object);
288 return *this;
289 }
size_t size() const override final
Get the size of the serializer content (in bytes).
JsonSerializer & update(U &object)
Update an existing object from the serializer.

Member Data Documentation

◆ _arrayIterators

std::stack<rapidjson::Value::ValueIterator> ecstasy::serialization::JsonSerializer::_arrayIterators
private

Stack of array iterators, to keep track of the current array element.

Definition at line 546 of file JsonSerializer.hpp.

◆ _document

rapidjson::Document ecstasy::serialization::JsonSerializer::_document
private

RapidJson document.

Definition at line 542 of file JsonSerializer.hpp.

◆ _nextKey

std::string ecstasy::serialization::JsonSerializer::_nextKey
private

Next key to use for the next object value.

Definition at line 550 of file JsonSerializer.hpp.

◆ _objectIterators

std::stack<rapidjson::Value::MemberIterator> ecstasy::serialization::JsonSerializer::_objectIterators
private

Stack of object iterators, to keep track of the current object element.

Definition at line 548 of file JsonSerializer.hpp.

◆ _stack

std::stack<std::reference_wrapper<rapidjson::Value> > ecstasy::serialization::JsonSerializer::_stack
private

Stack of nested objects or arrays, to keep track of the current context.

Definition at line 544 of file JsonSerializer.hpp.

◆ Close

constexpr NestedContextOp ecstasy::serialization::JsonSerializer::Close = NestedContextOp::Close
staticconstexpr

Close the current object or array.

Definition at line 58 of file JsonSerializer.hpp.

◆ NewArray

constexpr NestedContextOp ecstasy::serialization::JsonSerializer::NewArray = NestedContextOp::NewArray
staticconstexpr

Open a new array (Creating it in save mode)

Definition at line 56 of file JsonSerializer.hpp.

◆ NewObject

constexpr NestedContextOp ecstasy::serialization::JsonSerializer::NewObject = NestedContextOp::NewObject
staticconstexpr

Open a new object (Creating it in save mode)

Definition at line 54 of file JsonSerializer.hpp.


The documentation for this class was generated from the following file: