c++ JsonCpp Parse对Json字符串解析转换判断的补充 Json格式验证

最近在使用JsonCpp的时候,须要判断当前字符串是否为正确的Json格式,可是Jsoncpp对字符串进行认为是正确的json数据,致使获取的时候出错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 }
相关文章
相关标签/搜索