验证字符串是在asp.net JSON或不 [英] Validate a string to be json or not in asp.net

查看:133
本文介绍了验证字符串是在asp.net JSON或不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法来验证被JSON或不是一个字符串?除try / catch语句。

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

我使用ServiceStack JSON序列化,但没有找到相关的验证方法。

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

推荐答案

大概是最快和最肮脏的方法是检查是否字符串开头的{

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("]"); 
} 

另一种选择是,你可以尝试使用的JavaScriptSerializer类:

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

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

或者你可以看看JSON.NET:

Or you could have a look at JSON.NET:

这篇关于验证字符串是在asp.net JSON或不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆