bblanchon / ArduinoJson

📟 JSON library for Arduino and embedded C++. Simple and efficient.
https://arduinojson.org
MIT License
6.63k stars 1.1k forks source link

Identifying JsonVariant type of a deserialized document #2086

Closed HamzaHajeir closed 1 month ago

HamzaHajeir commented 2 months ago

Hi

I'm building an entity for serializing/deserializing from/to multiple formats for unknown schemes, one of them is JSON.

Over deserialization, I want to detect whether a JsonVariant holds an array by calling:

    std::string data; // The data source
    DynamicJsonDocument doc(1024);
    deserializeJson(doc, data);
    JsonObject root = doc.as<JsonObject>();
    for (JsonPair kv : root){
        std::string out_single;
        std::vector<std::string> out_multiple;
        if (kv.value().getData()->isArray()) /* Append out_multiple by looping inside it */;
        else out_single = kv.value().as<std::string>(); // It's an element, just use this instruction to fetch it.
    }

However, I can't perform this operation due to getData() method being unaccessable.

How can I perform such target using ArduinoJson (I'm on v6, but assume the latest: v7).

With Thanks, Hamza Hajeir

bblanchon commented 2 months ago

kv.value().is<JsonArray>()

HamzaHajeir commented 1 month ago

kv.value().is<JsonArray>()

Great, and getting it as array would be kv.value().as<JsonArray>().

It'd be also great to add this to docs or examples ;)

bblanchon commented 1 month ago

The documentation already says that kv.value() is a JsonVariant. What else do you need, and on which page?

HamzaHajeir commented 1 month ago

It's obviously clear to people already familiar with the library's design.

But to my experience, I couldn't find the solution in docs nor examples. But I've just found it under API Reference looking for is<>(), well, I wasn't aware of it.

Hope it helps. Hamza

On Mon, May 13, 2024, 10:33 Benoît Blanchon @.***> wrote:

The documentation already says that kv.value() is a JsonVariant. What else do you need, and on which page?

— Reply to this email directly, view it on GitHub https://github.com/bblanchon/ArduinoJson/issues/2086#issuecomment-2106854146, or unsubscribe https://github.com/notifications/unsubscribe-auth/AH3O7JZIYIL6H2VAFQKR543ZCBUFNAVCNFSM6AAAAABHJH6E2WVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCMBWHA2TIMJUGY . You are receiving this because you modified the open/close state.Message ID: @.***>