我试图在.Net 5应用程序中创建一个JSON对象。当我在VisualStudio2015qucik操作上使用VisualStudio2015qucik操作时,默认选项是Microsoft.AspNet.Mvc.Formatters.Json、Microsoft.Extensions.Configuration.Json和Newtonsoft.Json。我的理解是,Configuration.Json是用来读取表单appsettings.json的,所以它可能不是我用来创建JSON对象的工具。我找不到任何关于Formatters.Json的真实信息,如何使用它,或者它打算使用什么。Newtonsoft.Json是will文档,但是它比Formatters.Json更好吗?我该用哪两种?
发布于 2016-01-25 20:48:48
我将使用Json.Net来确定地创建JSON有效负载(毕竟,微软为Web做了)。
Nuget套餐资料来源:
Install-Package Newtonsoft.Json下面是一个例子。如果您想调用REST,在进行GET调用时返回一个产品,那么您可能会这样做。
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。
你可以使用第三方大会,使这个超级容易也。我们是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);
}发布于 2016-01-25 20:29:54
如果需要将对象序列化为json,则应使用NewtonSoft.Json。
发布于 2016-01-25 21:27:05
您不应该做任何特殊的事情来发送Json数据。默认的输出格式化程序已经是Json,如果您的Startup.cs文件有点正常,您应该有一行类似的代码:
services.AddMvc();默认情况下,这已经包含Json格式化程序,您的控制器应该根据浏览器要求的内容自动协商返回类型。因此,如下所示的控制器应该工作(取自这个吉特布问题,其中包含一些关于为什么/如何工作的信息):
public class ValuesController : ApiController
{
public SomeClass Get()
{
return new SomeClass();
}
public SomeClass Post([FromBody] SomeClass x)
{
return x;
}
}https://stackoverflow.com/questions/35001701
复制相似问题