Correct way to parse JSON values vie cpprestsdk

问题内容:

Trying to figure out a general to-go way for JSON value parsing.

  • No error checking:

    myField = jsonValue["myField"].as_string();`
    
  • With error checking:

    if (jsonValue.is_null())
        return false;
    
    if (!jsonValue.is_object())
        return false;
    
    for (auto it = jsonValue.as_object().cbegin(); it != jsonValue.as_object().cend(); ++it)
    {
        const std::string& str = it->first;
        const json::value& v = it->second;
    
        if (str == "myField")
        {
            if (v.is_string())
            {
                myField = v.as_string();
                continue;
            }
            else
            {
                return false;
            }
        }
    }
    

The difference in amount of code is noticeable. Should I bother with error checking or the first approach would be enough?

问题评论:

    
Maybe validate your json with a json-schema before processing it ?

答案:

答案1:

This question would probably be best suited at https://codereview.stackexchange.com/ but if you have a requirement to handle errors gracefully, you should prefer code that has robust error handling.

答案评论:

原文地址:

https://stackoverflow.com/questions/47755986/correct-way-to-parse-json-values-vie-cpprestsdk

添加评论

友情链接:蝴蝶教程