Minh Nguyen / ArduinoJson
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers PrettyJsonSerializer.hpp Source File

PrettyJsonSerializer.hpp

00001 // ArduinoJson - arduinojson.org
00002 // Copyright Benoit Blanchon 2014-2021
00003 // MIT License
00004 
00005 #pragma once
00006 
00007 #include <ArduinoJson/Configuration.hpp>
00008 #include <ArduinoJson/Json/JsonSerializer.hpp>
00009 #include <ArduinoJson/Serialization/measure.hpp>
00010 #include <ArduinoJson/Serialization/serialize.hpp>
00011 
00012 namespace ARDUINOJSON_NAMESPACE {
00013 
00014 template <typename TWriter>
00015 class PrettyJsonSerializer : public JsonSerializer<TWriter> {
00016   typedef JsonSerializer<TWriter> base;
00017 
00018  public:
00019   PrettyJsonSerializer(TWriter &writer) : base(writer), _nesting(0) {}
00020 
00021   size_t visitArray(const CollectionData &array) {
00022     VariantSlot *slot = array.head();
00023     if (slot) {
00024       base::write("[\r\n");
00025       _nesting++;
00026       while (slot != 0) {
00027         indent();
00028         slot->data()->accept(*this);
00029 
00030         slot = slot->next();
00031         base::write(slot ? ",\r\n" : "\r\n");
00032       }
00033       _nesting--;
00034       indent();
00035       base::write("]");
00036     } else {
00037       base::write("[]");
00038     }
00039     return this->bytesWritten();
00040   }
00041 
00042   size_t visitObject(const CollectionData &object) {
00043     VariantSlot *slot = object.head();
00044     if (slot) {
00045       base::write("{\r\n");
00046       _nesting++;
00047       while (slot != 0) {
00048         indent();
00049         base::visitString(slot->key());
00050         base::write(": ");
00051         slot->data()->accept(*this);
00052 
00053         slot = slot->next();
00054         base::write(slot ? ",\r\n" : "\r\n");
00055       }
00056       _nesting--;
00057       indent();
00058       base::write("}");
00059     } else {
00060       base::write("{}");
00061     }
00062     return this->bytesWritten();
00063   }
00064 
00065  private:
00066   void indent() {
00067     for (uint8_t i = 0; i < _nesting; i++) base::write(ARDUINOJSON_TAB);
00068   }
00069 
00070   uint8_t _nesting;
00071 };
00072 
00073 template <typename TSource, typename TDestination>
00074 size_t serializeJsonPretty(const TSource &source, TDestination &destination) {
00075   return serialize<PrettyJsonSerializer>(source, destination);
00076 }
00077 
00078 template <typename TSource>
00079 size_t serializeJsonPretty(const TSource &source, void *buffer,
00080                            size_t bufferSize) {
00081   return serialize<PrettyJsonSerializer>(source, buffer, bufferSize);
00082 }
00083 
00084 template <typename TSource>
00085 size_t measureJsonPretty(const TSource &source) {
00086   return measure<PrettyJsonSerializer>(source);
00087 }
00088 
00089 }  // namespace ARDUINOJSON_NAMESPACE