c# - 如何从服务器端代码反序列化 JSON

标签 c# jquery asp.net

假设我的 json 存储在字符串变量中。我的 json 看起来像

"{\"file\":\"dave\",\"type\":\"ward\"}"

上面的数据存储在我的字符串变量中。现在我如何反序列化此 json 数据并读取每个组件,如文件和类型。

我尝试了下面的代码但出现了错误

 var jss = new JavaScriptSerializer();
 string json = new StreamReader(context.Request.InputStream).ReadToEnd();

 var sData=jss.Deserialize<string>(json);
 string _file = sData[0].ToString();
 string _type = sData[1].ToString();

请指导我如何从 json 格式的数据反序列化后提取文件和类型等每个组件。谢谢


整改

我通过这种方式解决了这个问题....这是完整的客户端和服务器端代码。

     <script type="text/javascript">
     $(document).ready(function () {
         $('#btnlogin').click(function (e) {
             var FeedCrd = {};
             FeedCrd["file"] = 'dave';
             FeedCrd["type"] = 'ward';

             $.ajax({
                 type: "POST",
                 url: "CallASHX.ashx",
                 data: JSON.stringify(FeedCrd),
                 //data: { 'file': 'dave', 'type': 'ward' },
                 //dataType: "json",
                 success: function (data) {
                     if (data == "SUCCESS");
                     {
                         alert('SUCCESS');
                     }

                 },
                 error: function (XMLHttpRequest, textStatus, errorThrown) {
                     alert(textStatus);
                 }

             });
             return false;
         });
     });
 </script>

public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        var jss = new JavaScriptSerializer();
        string json = new StreamReader(context.Request.InputStream).ReadToEnd();
        Dictionary<string,string> sData=jss.Deserialize<Dictionary<string,string>>(json);
        string _file = sData["file"].ToString();
        string _type = sData["type"].ToString();
        context.Response.Write("SUCCESS");
    }

最佳答案

我发现的最简单的方法是结合 Json.NET带有新 .net 的库 dynamic对象类型:

string json = "{\"file\":\"dave\",\"type\":\"ward\"}";
dynamic jo = JObject.Parse(json);
string _file = jo.file;
string _type = jo.type;

不要忘记:

using Newtonsoft.Json.Linq;

这是一种非常简单的方法,您不必声明强类型对象,因此可以简单地即时执行。

关于c# - 如何从服务器端代码反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12589409/

相关文章:

javascript - 无法通过JS获取输入值

jquery - 如何使用 jquery .mouseleave 事件调用函数

javascript - D3 : adding style and class to DIV results in styles discarded

c# - 如果程序最小化或在系统托盘中,如何检测 ctrl 键被按下两次

c# - C# 中是否有任何函数返回与卡方拟合优度检验相关的 p 值?

c# - 锁定集合与 syncRoot 相比有什么缺点吗?

c# - ASP.NET MVC4 模型的子集合下拉列表未正确绑定(bind)

c# - 您正在使用通过 http 下载的方式。目前 Unity 将 NSAllowsArbitraryLoads 添加到 Info.plist 以简化转换

asp.net - asp.net IIS 7.0 或更高版本中 maxConcurrentThreadsPerCPU 的默认值是多少?

c# - 将 Asp.net MVC5 Razor 代码存储在数据库中并处理以在运行时获取值