1

I'm using nlohmann::json to parse json string. I implement a util function GetValue() to retrieve object fields.

template<typename T1, typename T2>
bool CheckType(T1& it, T2& val) { return false; }

template<typename T1>
bool CheckType(T1& it, bool& val) { return it->is_boolean(); }

template<typename T1>
bool CheckType(T1& it, std::string& val) { return it->is_string(); }

....

template<typename T>
bool GetValue(nlohmann::json obj, std::string key, T& value, std::string &err) {
    auto it = obj.find(key);
    if (it != obj.end()) {
        if (CheckType(it, val)) {
            value = it->get<T>();
            return true;
        } else {
            err = key + " type error";
        }
    } else {
        err = key + " not found";
    }
    return false;
}

The function CheckType() looks ugly. What's the elegant way to do this?

1 Answer 1

1

Not sure but, if the get() support a throwing in case of bad type, It seems to me simpler write something as

template<typename T>
bool GetValue(nlohmann::json obj, std::string key, T& value, std::string &err) {
    auto it = obj.find(key);
    if (it != obj.end()) {
       try {
          value = it->get<T>();
          return true;
       }
       catch (...) { // catching the correct exception; see library documentation
           err = key + " type error";
       }
    } else
        err = key + " not found";

    return false;
}

completely avoiding the CheckType() functions.

Sign up to request clarification or add additional context in comments.

2 Comments

using exception is a good idea for this case:). but I still want to find a better way to call different functions according to different T.
@jasonxia - here the problem if the lack (I suppose) of a method of type isType<T>() (or, maybe better, isConvertibleTo<T>()) in the library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.