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

后端 未结 3 1104
长情又很酷
长情又很酷 2021-01-05 10:49

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 valid

3条回答
  •  星月不相逢
    2021-01-05 11:29

    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(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

提交回复
热议问题