在asp.net中验证字符串是否为json

2023-11-23

有什么方法可以验证字符串是否为 json 吗?除了 try/catch 之外。

我正在使用 ServiceStack Json Serializer,但找不到与验证相关的方法。


可能最快和最肮脏的方法是检查字符串是否以'{':

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

另一种选择是您可以尝试使用 JavascriptSerializer 类:

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

或者你可以看看 JSON.NET:

  • http://james.newtonking.com/projects/json-net.aspx
  • http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在asp.net中验证字符串是否为json 的相关文章

随机推荐