c# - 如何从 ASP.net MVC 程序中获取普通 c# 程序中的 JSON 数据?

标签 c# asp.net asp.net-mvc json web-services

我是 asp.net MVC 的新手。我想创建一个普通的 c# 客户端程序,它使用从 asp.net mvc 程序返回的 json。从 asp.net MVC 站点检索 json 数据的最佳方法是什么?我目前使用 WebRequst、WebResponse 和 StreamReader 来检索数据。这是一个好方法,否则获取数据的最佳做法是什么?我可以使用类似下面的东西吗?非常感谢

    WebRequest request = HttpWebRequest.Create(url);
    WebResponse response = request.GetResponse();  
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string urlText = reader.ReadToEnd();
    //Then parse the urlText to json object

最佳答案

您不会在服务器端将文本解析为 JSON 对象,因为 JSON 是 Javascript Object Notation 而 C# 对此一无所知。您将 JSON 字符串解析为特定类型。例如:

string json = {"Name":"John Smith","Age":34};

可以这样反序列化为 C# 类 Person:

public class Person
{
   public string Name {get;set;}
   public int Age {get;set;}
}

JavascriptSerializer js= new JavascriptSerializer();
Person john=js.Desearialize<Person>(json);

关于c# - 如何从 ASP.net MVC 程序中获取普通 c# 程序中的 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7930620/

相关文章:

c# - dataGridView1.Columns.Clear() 抛出 IndexOutOfRange 异常

asp.net - IE8 下的慢 javascript

ASP.NET:无法验证数据

asp.net-mvc - 你用 ReSharper 做什么?

c# - 如何以编程方式将属性为 "Template"的 Setter 添加到 C#/WPF 中的触发器?

c# - 在 asp net mvc 中清除重定向的哈希和参数?

asp.net-mvc - 使用 EditorFor 时将值添加到 ModelMetadata.AdditionalValues

c# - ViewResult 不使用 ASP.NET MVC 在 ASP.NET WebForms 项目中呈现页面内容

c# - .NET Azure.Identity SDK 网络超时

c# - Microsoft.Web.Administration.Site 在调用方法 Stop() 时抛出 NotImplemenetedException