c++ JsonCpp Parse對Json字符串解析轉換判斷的補充 Json格式驗證


最近在使用JsonCpp的時候,需要判斷當前字符串是否為正確的Json格式,但是Jsoncpp對字符串進行認為是正確的json數據,導致獲取的時候出錯

添加一個驗證的方法,在轉換之前,提前驗證數據是否正確,正確之后才能進行轉換

  1 bool IsJsonIllegal(const char *jsoncontent)
  2 {
  3     std::stack<char> jsonstr;
  4     const char *p = jsoncontent;
  5     char startChar = jsoncontent[0];
  6     char endChar = '\0';
  7     bool isObject = false;//防止 {}{}的判斷
  8     bool isArray = false;//防止[][]的判斷
  9 
 10     while (*p != '\0')
 11     {
 12         endChar = *p;
 13         switch (*p)
 14         {
 15         case '{':
 16             if (!isObject)
 17             {
 18                 isObject = true;
 19             }
 20             else  if (jsonstr.empty())//對象重復入棧
 21             {
 22                 return false;
 23             }
 24             jsonstr.push('{');
 25             break;
 26         case '"':
 27             if (jsonstr.empty() || jsonstr.top() != '"')
 28             {
 29                 jsonstr.push(*p);
 30             }
 31             else
 32             {
 33                 jsonstr.pop();
 34             }
 35             break;
 36         case '[':
 37             if (!isArray)
 38             {
 39                 isArray = true;
 40             }
 41             else  if (jsonstr.empty())//數組重復入棧
 42             {
 43                 return false;
 44             }
 45             jsonstr.push('[');
 46             break;
 47         case ']':
 48             if (jsonstr.empty() || jsonstr.top() != '[')
 49             {
 50                 return false;
 51             }
 52             else
 53             {
 54                 jsonstr.pop();
 55             }
 56             break;
 57         case '}':
 58             if (jsonstr.empty() || jsonstr.top() != '{')
 59             {
 60                 return false;
 61             }
 62             else
 63             {
 64                 jsonstr.pop();
 65             }
 66             break;
 67         case '\\'://被轉義的字符,跳過
 68             p++;
 69             break;
 70         default:
 71             ;
 72         }
 73         p++;
 74     }
 75 
 76     if (jsonstr.empty())
 77     {
 78         //確保是對象或者是數組,之外的都不算有效 
 79         switch (startChar)//確保首尾符號對應
 80         {
 81         case  '{':
 82         {
 83             if (endChar = '}')
 84             {
 85                 return true;
 86             }
 87             return false;
 88         }
 89         case '[':
 90         {
 91             if (endChar = ']')
 92             {
 93                 return true;
 94             }
 95             return false;
 96         }
 97         default:
 98             return false;
 99         }
100 
101         return true;
102     }
103     else
104     {
105         return false;
106     }
107 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM