有没有办法验证字符串是否为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