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
class JsonBuilder::Impl {
public:
Impl() {
JsonBuilder::JsonBuilder()
: doc_(
#ifdef USE_PSRAM
allocator_ = std::make_unique<SpiRamAllocator>();
doc_ = std::make_unique<JsonDocument>(allocator_.get());
(allocator_ = std::make_unique<SpiRamAllocator>(), allocator_.get())
#else
doc_ = std::make_unique<JsonDocument>();
nullptr
#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() {
if (impl_->overflowed()) {
if (doc_.overflowed()) {
ESP_LOGE(TAG, "JSON document overflow");
return "{}";
}
std::string output;
impl_->serialize_to(output);
serializeJson(doc_, output);
return output;
}

View File

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