1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-23 13:42:27 +01:00
This commit is contained in:
J. Nick Koston
2025-09-15 20:49:22 -05:00
parent c203f61e6b
commit 290c2e17f5
2 changed files with 22 additions and 40 deletions

View File

@@ -70,50 +70,23 @@ bool parse_json(const std::string &data, const json_parse_t &f) {
} }
// JsonBuilder implementation // JsonBuilder implementation
class JsonBuilder::Impl { JsonBuilder::JsonBuilder()
public: : doc_(
Impl() {
#ifdef USE_PSRAM #ifdef USE_PSRAM
allocator_ = std::make_unique<SpiRamAllocator>(); (allocator_ = std::make_unique<SpiRamAllocator>(), allocator_.get())
doc_ = std::make_unique<JsonDocument>(allocator_.get());
#else #else
doc_ = std::make_unique<JsonDocument>(); nullptr
#endif #endif
) {
} }
JsonObject root() {
if (!root_created_) {
root_ = doc_->to<JsonObject>();
root_created_ = true;
}
return root_;
}
bool overflowed() const { return doc_->overflowed(); }
void serialize_to(std::string &output) { serializeJson(*doc_, output); }
private:
#ifdef USE_PSRAM
std::unique_ptr<SpiRamAllocator> allocator_;
#endif
std::unique_ptr<JsonDocument> doc_;
JsonObject root_;
bool root_created_{false};
};
JsonBuilder::JsonBuilder() : impl_(std::make_unique<Impl>()) {}
JsonBuilder::~JsonBuilder() = default;
JsonObject JsonBuilder::root() { return impl_->root(); }
std::string JsonBuilder::serialize() { std::string JsonBuilder::serialize() {
if (impl_->overflowed()) { if (doc_.overflowed()) {
ESP_LOGE(TAG, "JSON document overflow"); ESP_LOGE(TAG, "JSON document overflow");
return "{}"; return "{}";
} }
std::string output; std::string output;
impl_->serialize_to(output); serializeJson(doc_, output);
return output; return output;
} }

View File

@@ -29,15 +29,24 @@ bool parse_json(const std::string &data, const json_parse_t &f);
class JsonBuilder { class JsonBuilder {
public: public:
JsonBuilder(); JsonBuilder();
~JsonBuilder();
JsonObject root(); JsonObject root() {
if (!root_created_) {
root_ = doc_.to<JsonObject>();
root_created_ = true;
}
return root_;
}
std::string serialize(); std::string serialize();
private: private:
// Use opaque pointer to hide implementation details #ifdef USE_PSRAM
class Impl; std::unique_ptr<ArduinoJson::Allocator> allocator_;
std::unique_ptr<Impl> impl_; #endif
JsonDocument doc_;
JsonObject root_;
bool root_created_{false};
}; };
} // namespace json } // namespace json