简体   繁体   English

有没有一种方法可以验证C#中的字符串是否为JSON格式?

[英]Is there a way to validate if a String is JSON format in C#?

I tried using code I found in this answer :- 我尝试使用在此答案中找到的代码 :-

        strInput = strInput.Trim();
        if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
            (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
        {
            try
            {
                var obj = JToken.Parse(strInput);
                return true;
            }
            catch (JsonReaderException jex)
            {
                //Exception in parsing json
                Console.WriteLine(jex.Message);
                return false;
            }
            catch (Exception ex) //some other exception
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }
        else
        {
            return false;
        }

Problem with this code is, that it validates wrong JSON Files as right, because JToken.Parse automatically deletes Elements that are doubled in the sequence for example: 这段代码的问题在于,它会正确验证错误的JSON文件,因为JToken.Parse会自动删除序列中加倍的元素,例如:

{
   "Body" : {
      "Data" : {}
   },
   "Head" : {
      "RequestArguments" : {
         "Scope" : ""
      },
      "Status" : {
         "Code" : 255,
         "Reason" : "CGI-Args: Invalid parameter '' for Scope.",
         "UserMessage" : ""
      },
      "Timestamp" : "2017-01-24T13:15:33+01:00"
   },
   "Head" : {
      "RequestArguments" : {
         "Scope" : ""
      },
      "Status" : {
         "Code" : 255,
         "Reason" : "CGI-Args: Invalid parameter '' for Scope.",
         "UserMessage" : ""
      },
      "Timestamp" : "2017-01-24T13:15:33+01:00"
   }
}

Here there are 2 Head Token on the same Level which are not allowed, but JToken automatically parses away one of the 2 Head Tokens so the resulting Object is valid 这里不允许在同一级别上有2个Head Token,但是JToken会自动解析2个Head Token之一,因此生成的Object有效

You can modify this code to check elements from JToken.Parse() result. 您可以修改此代码以检查JToken.Parse()结果中的元素。 If values are duplicated you can return false 如果值重复,则可以返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM