Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: JsonString.as<T>() #1964

Open
razvanphp opened this issue Sep 11, 2023 · 4 comments
Open

Feature request: JsonString.as<T>() #1964

razvanphp opened this issue Sep 11, 2023 · 4 comments

Comments

@razvanphp
Copy link

razvanphp commented Sep 11, 2023

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

@bblanchon
Copy link
Owner

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

@razvanphp
Copy link
Author

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.

@bblanchon
Copy link
Owner

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.

@razvanphp
Copy link
Author

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 馃檪

@bblanchon bblanchon changed the title Feature request: JsonPair.key().as<Type>() Feature request: JsonString.as<T>() Sep 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants