【问题标题】:Creating a JSON object in ASP.Net在 ASP.Net 中创建 JSON 对象
【发布时间】:2016-01-25 20:26:35
【问题描述】:

我正在尝试在 .Net 5 应用程序中创建 JSON 对象。当我在 Json 上使用 Visual Studio 2015 Qucik Actions 时,我看到的默认选项是 Microsoft.AspNet.Mvc.Formatters.JsonMicrosoft.Extensions.Configuration.JsonNewtonsoft.Json。我的理解是Configuration.Json 用于读取appsettings.json 的形式,所以它可能不是我用来创建JSON 对象的方法。我找不到关于Formatters.Json 的任何真实信息,如何使用它,或者它的用途是什么。 Newtonsoft.Json 将记录在案,但它是否比 Formatters.Json 更好?我应该使用这两者中的哪一个?

【问题讨论】:

  • 这个问题已经被问过(和回答)很多次了。在我看来,最好的选择(性能、功能、支持等)是使用Json.Net。只需将其添加到您的 bower 文件中即可。请注意,重复的问题是关于 .NET 4 但仍适用于 ASP.NET Core。
  • @LeonardoHerrera 这不是重复的。 .Net 4 和 .Net core 有不同的包,其中两个是 .Net 5 的新包。是的,Netwonsoft 是针对 .Net 4 的,但另外两个不是,所以最好的方法可能已经针对 .Net 5 进行了更改
  • 嗯。请更好地说明您的问题:我不确定应该使用哪一个来构建 Json 对象 不是 a/b 问题,因为有很多选项。你有没有尝试过 Json.Net?
  • 我撤回了我的投票,但仍然认为您需要详细说明一下。关于输出格式化程序,您的 config.json 文件中有什么?
  • @LeonardoHerrera 我已经重写了这个问题,希望它更容易理解。至于输出格式化程序,我没有 config.json 文件,但同时查看 appsettings.jsonproject.json 我没有看到任何暗示它是输出格式化程序的东西。

标签: c# json asp.net-core


【解决方案1】:

直接取自ASP.NET Core 1 tests

var 预期 = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { foo = "abcd" }));

同样采用from the tests并稍作修改,用HttpClient调用它,看看如何将你的json字符串发送到服务器。

var response = 等待 Client.PostAsync( "http://localhost/api/ActionUsingSpecificFormatters", 新的 StringContent(yourJsonContent, Encoding.UTF8, "application/json"));

按照Newtonsoft,你可以简单地编码,然后做任何你想做的事情。

产品产品 = 新产品(); product.Name = "苹果"; product.ExpiryDate = new DateTime(2008, 12, 28); 产品.价格 = 3.99M; product.Sizes = new string[] { "Small", "Medium", "Large" }; 字符串输出 = JsonConvert.SerializeObject(product); //{ // "名称": "苹果", // "ExpiryDate": "2008-12-28T00:00:00", // "价格": 3.99, //“尺寸”:[ // “小的”, // “中等的”, // “大” // ] //} 产品反序列化产品 = JsonConvert.DeserializeObject(输出);

把它们放在一起 - 我刚刚测试了这个。请记住,这是来自 MVC 6(ASP.NET 5 即 ASP.NET Core 1)的真正通用直通测试:)

[HttpGet] 公共异步任务 Get() { var client = new HttpClient(); var customer = new Customer() { Name = "Schmo", Address = "1999 Purple Rain St" }; var customerJson = JsonConvert.SerializeObject(客户); var response = 等待 client.PostAsync( "http://localhost:4815/api/Customer", 新 StringContent(customerJson, Encoding.UTF8, "application/json")); //只是一些模板输出来测试我要回来的。 字符串 resultJson = "{'Name':'adam'}"; if (response.StatusCode == HttpStatusCode.OK) { resultJson = 等待 response.Content.ReadAsStringAsync(); var updatedCustomer = JsonConvert.DeserializeObject(resultJson); } 返回结果Json; } 公共类客户 { 公共字符串名称 { 获取;放; } 公共字符串地址 { 获取;放; } }

【讨论】:

  • 您的第一个建议不适用,因为它已过时。您的链接是 WebAPI 2 教程,我不要求 WebAPI 2。在 ASP.Net 5 HttpClient 中只有 PostAsync 方法而不是 PostAsJsonAsync。我可以在 Netwonsoft 上找到很多信息,但在 Formatters.Json 上几乎没有,所以我不确定哪个对我们更好。
  • 第一个建议是从客户端调用 webapi - 这似乎是你正在做的 - 你的客户端是 asp..net - 不是吗? ASP.NET 5 有 json.net(在我们的 box 模板中)——一个新版本刚刚专门为它发布。
  • 是的,但你的答案仍有一半是错误的。 HttpClient 不再有 PostAsJsonAsync,因此该教程将不起作用。
  • 在上面编辑和简化(错过了最初的 asp.net 5)
【解决方案2】:

我肯定会使用 Json.Net 来创建 JSON 有效负载(毕竟,Microsoft 是为 Web Api 做的)。

Nuget 包来源:

Install-Package Newtonsoft.Json

这是一个例子。如果您想在进行 GET 调用时调用返回产品的 REST api,那么您可以执行类似的操作。

public static class Main
{
    string url = "https://TheDomainYouWantToContact.com/products/1";
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.Method = "GET";
    request.ContentType = "application/json";
    request.Accept = "application/json";
    var httpResponse = (HttpWebResponse)request.GetResponse();

    var dataStream = httpResponse.GetResponseStream();
    var reader = new StreamReader(dataStream);
    var responseFromServer = reader.ReadToEnd();
    reader.Close();
    dataStream.Close();

    // This is the code that turns the JSON string into the Product object.
    Product productFromServer = JsonConvert.Deserialize<Product>(responseFromServer);
    Console.Writeline(productFromServer.Id);
}

// This is the class that represents the JSON that you want to post to the service.
public class Product
{
    public string Id { get; set; }
    public decimal Cost { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

同样的方法也可以用于 POST 和 PUT。

您也可以使用 3rd 方程序集来让这变得超级简单。我们是 DynamicApis.Api 的作者

Install-Package DynamicApis.Api

使用此客户端发出相同请求的代码如下:

public static class Main
{
    RestClient client = new RestClient();
    string url = "https://YourDomain.com/products/1";
    var productFromServer = client.Get<Product>(url);
    Console.Writeline(productFromServer.Id);
}

【讨论】:

    【解决方案3】:

    如果你需要将对象序列化为 json,你应该使用 NewtonSoft.Json

    【讨论】:

    • 您能否详细说明为什么是那个而不是Formatters.JsonFormatters.Json 上没有太多详细信息,所以我无法比较/对比它们,
    • 实际上我的回答可能太仓促了,因为 Formatters.Json 正在使用 Newtonsoft.Json,所以我认为您可以使用其中任何一个,但可能应该只使用 Formatters.Json,除非您需要这样做一些特别的东西
    • 你有使用Formatters.Json的例子吗?我不能对它执行“转到定义”,并且我没有得到任何关于它的重载方法的 Intellisense。
    • 看看我的项目代码中从第 290 行开始的方法,我在那里返回 json github.com/joeaudette/cloudscribe/blob/master/src/…
    【解决方案4】:

    您不需要做任何特别的事情来发回 Json 数据。默认的输出格式化程序已经是 Json,如果你的 Startup.cs 文件有些正常,你应该有类似这样的一行:

    services.AddMvc();
    

    默认情况下,这已经包含 Json 格式化程序,并且您的控制器应该根据浏览器的要求自动协商返回类型。所以像下面这样的控制器应该可以工作(取自this Github issue,其中包含一些关于为什么/如何工作的信息):

    public class ValuesController : ApiController
    {
        public SomeClass Get()
        {
            return new SomeClass();
        }
    
        public SomeClass Post([FromBody] SomeClass x)
        {
            return x;
        }
    }
    

    【讨论】:

    • 您假设此 Json 对象将始终传递给我自己的应用程序,并且说应用程序具有 API。虽然您的回复在这种情况下有效,但并非在所有情况下都有效。在这种情况下,JSON 将被传递给第三方的 API 或 JavaScript AJAX 响应。
    • 那我这里就不知所措了。那你为什么要 Json 格式化程序呢?
    • 我感觉你的问题带有太多的包袱。你需要做什么?将一些 Json 数据发布到第三方 API?如果是这样,那么您应该使用 Json.Net
    • 在这种特殊情况下,它将被发布到第三方 API。 Json.NetNewtonsoft.Json 是一样的吗?
    • @LeonardoHerrera 它没有发回 json,而是序列化 json。 Matt - Json.Net 是 newtonsoft :)
    猜你喜欢
    • 2012-09-04
    • 1970-01-01
    • 2012-04-01
    • 2021-10-22
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2021-11-08
    • 2020-05-10
    相关资源
    最近更新 更多