ArduinoJson icon indicating copy to clipboard operation
ArduinoJson copied to clipboard

Feature request: JsonString.as<T>()

Open razvanphp opened this issue 2 years ago • 4 comments

Hey, thank you for your great work!

It would be a lot easier (and cleaner) if this functionality would be implemented 🙂

Currently, only the .value() has it as it is implemented in JsonVariant.

My code snippet:

for (JsonPair el : json.as<JsonObject>()) {
    Serial.println(atoi(el.key().c_str()));
    Serial.println(el.value().as<int>());
}

Cheers, R

razvanphp avatar Sep 11 '23 14:09 razvanphp

Hi @razvanphp,

key() is a string (a JsonString to be exact), why would you expect it to have the same interface as a variant?

Best regard, Benoit

bblanchon avatar Sep 12 '23 06:09 bblanchon

I do not expect that, I was just suggesting that this convenience method would serve in some cases when the key is actually of different type than string, avoiding extra operations like atoi.

razvanphp avatar Sep 12 '23 11:09 razvanphp

So, you're asking for JsonString::as<int>(), right?

I must say that I'm not fond of this idea:

  1. It blurs the message that JsonString is a string and not a JsonVariant.
  2. It would work for double and bool as well, but I doubt anyone will ever use it.
  3. It would not work for JsonArray and JsonObject even if the key contains a JSON array/object, and even if it worked, who would do that?

I'm sorry, but I'll need to see some very convincing code examples before adding something like that in the library.

bblanchon avatar Sep 13 '23 07:09 bblanchon

Well, I was using it just for int, as you can see above in my code snippet, because I was setting registers in arduino and the key in json is not valid as integer, it needs to be string.

Indeed JsonString is a string representation, but one would still need to call c_str() to really use it as a string, why wouldn't it be another convenience method to convert to any other type?

Obviously It's your call and feel free to discard my suggestion 🙂

razvanphp avatar Sep 13 '23 09:09 razvanphp