Validate a string to be json or not in asp.net

陌路散爱 提交于 2019-12-30 09:01:48

问题


is there any way to validate a string to be json or not ? other than try/catch .

I'm using ServiceStack Json Serializer and couldn't find a method related to validation .


回答1:


Probably the quickest and dirtiest way is to check if the string starts with '{':

public static bool IsJson(string input){ 
    input = input.Trim(); 
    return input.StartsWith("{") && input.EndsWith("}")  
           || input.StartsWith("[") && input.EndsWith("]"); 
} 

Another option is that you could try using the JavascriptSerializer class:

JavaScriptSerializer ser = new JavaScriptSerializer(); 
SomeJSONClass = ser.Deserialize<SomeJSONClass >(json); 

Or you could have a look at JSON.NET:

  • http://james.newtonking.com/projects/json-net.aspx
  • http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm



回答2:


A working code snippet

public bool isValidJSON(String json)
{
    try
    {
        JToken token = JObject.Parse(json);
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

Source




回答3:


You can find a couple of regular expressions to validate JSON over here: Regex to validate JSON

It's written in PHP but should be adaptable to C#.



来源:https://stackoverflow.com/questions/11835593/validate-a-string-to-be-json-or-not-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!