Skip to content

Commit

Permalink
add parseAs
Browse files Browse the repository at this point in the history
  • Loading branch information
dankmeme01 committed Nov 14, 2024
1 parent a6784db commit 7fc9d98
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions include/matjson.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,19 @@ namespace matjson {
/// @return The parsed JSON value or an error
static geode::Result<Value, ParseError> parse(std::string_view source);

/// Parses JSON from a string and tries to convert it to a given type
/// @param source The JSON string to parse
/// @return The parsed struct or an error
template <CanDeserialize T>
inline static geode::Result<T> parseAs(std::string_view source) {
auto parsed = Value::parse(source);
if (!parsed) {
return geode::Err(static_cast<std::string>(parsed.unwrapErr()));
}

return Serialize<T>::fromJson(parsed.unwrap());
}

/// Parses JSON from an input stream
/// @param source Stream to parse
/// @return The parsed JSON value or an error
Expand Down Expand Up @@ -359,6 +372,15 @@ namespace matjson {
return Value::parse(source);
}

/// Parses JSON from a string and tries to convert it to a given type
/// @param source The JSON string to parse
/// @return The parsed struct or an error
/// @note Shorthand for Value::parse<T>
template <CanDeserialize T>
inline geode::Result<T> parseAs(std::string_view source) {
return Value::parseAs<T>(source);
}

/// Parses JSON from an input stream
/// @param source Stream to parse
/// @return The parsed JSON value or an error
Expand Down

0 comments on commit 7fc9d98

Please sign in to comment.