I am trying to create a JSON object in a .Net 5 application. The default options I am presented with are Microsoft.AspNet.Mvc.Formatters.Json
, Microsoft.Extensions.Configuration.Json
, and Newtonsoft.Json
when I use the Visual Studio 2015 Qucik Actions on Json
. My understanding is that Configuration.Json
is for reading form the appsettings.json
so it probably is not what I would use to create a JSON object. I can't find any real information on Formatters.Json
, how to use it, or what it's intended use it. Newtonsoft.Json
is will documented but is it better over the Formatters.Json
? Which of the two should I be using?
4 Answers
Taken directly from ASP.NET Core 1 tests
var expected = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { foo = "abcd" }));
Also taken from the tests and slightly modified, call it with HttpClient to see how to send your json string to the server.
var response = await Client.PostAsync( "http://localhost/api/ActionUsingSpecificFormatters", new StringContent(yourJsonContent, Encoding.UTF8, "application/json"));
As per Newtonsoft you can simply encode, then do whatever you want after that.
Product product = new Product(); product.Name = "Apple"; product.ExpiryDate = new DateTime(2008, 12, 28); product.Price = 3.99M; product.Sizes = new string[] { "Small", "Medium", "Large" }; string output = JsonConvert.SerializeObject(product); //{ // "Name": "Apple", // "ExpiryDate": "2008-12-28T00:00:00", // "Price": 3.99, // "Sizes": [ // "Small", // "Medium", // "Large" // ] //} Product deserializedProduct = JsonConvert.DeserializeObject(output);
Putting it all together - I just tested this. Keep in mind this is a real generic pass through test from MVC 6 (ASP.NET 5 ie ASP.NET Core 1) :)
[HttpGet] public async Task<string> Get() { var client = new HttpClient(); var customer = new Customer() { Name = "Schmo", Address = "1999 Purple Rain St" }; var customerJson = JsonConvert.SerializeObject(customer); var response = await client.PostAsync( "http://localhost:4815/api/Customer", new StringContent(customerJson, Encoding.UTF8, "application/json")); //just some template output to test which I'm getting back. string resultJson = "{ 'Name':'adam'}"; if (response.StatusCode == HttpStatusCode.OK) { resultJson = await response.Content.ReadAsStringAsync(); var updatedCustomer = JsonConvert.DeserializeObject(resultJson); } return resultJson; } public class Customer { public string Name { get; set; } public string Address { get; set; } }
- Your first suggestions does not apply as it is out of date. Your link is to a WebAPI 2 tutorial and I am not asking for WebAPI 2. In ASP.Net 5
HttpClient
only has aPostAsync
method not aPostAsJsonAsync
. And I was able to find a lot of info on Netwonsoft but almost none onFormatters.Json
so I was not sure which was better to us.CommentedJan 25, 2016 at 20:47 - the first suggestion was calling webapi from a client - which is what it seems you are doing - your client is asp..net - no? ASP.NET 5 has json.net with it (in our of box templates) - a new version was just released specifically for it.CommentedJan 25, 2016 at 21:04
- Yes but half your answer is still wrong.
HttpClient
no longer hasPostAsJsonAsync
so that tutorial will not work.CommentedJan 25, 2016 at 21:25 - edited above and simplified (missed the initial asp.net 5)CommentedJan 25, 2016 at 22:15
I would use Json.Net to create the JSON payloads for sure (Afterall, Microsoft does for Web Api).
Nuget Package Source:
Install-Package Newtonsoft.Json
Here is an example. If you want to call a REST api that returns a product when you make a GET call then you might do something like this.
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; } }
The exact same method can be used for POST and PUT as well.
You can use 3rd party assemblies to make this super easy too. We are the authors of DynamicApis.Api
Install-Package DynamicApis.Api
The code to make the same request using this client would be:
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); }
you should use NewtonSoft.Json if you need to serialize objects as json
- Can you elaborate on why that one and not the
Formatters.Json
? There is not really much detail info onFormatters.Json
so I can't compare/contrast them,CommentedJan 25, 2016 at 20:34 - actually I was probably too hasty with my answer, under the hood Formatters.Json is using Newtonsoft.Json so I think you could use either one but probably should just use Formatters.Json unless you need to do something specialCommentedJan 25, 2016 at 20:47
- Do you have any examples of using
Formatters.Json
? I can't do a "Go To Definitions" on it and I am not getting any Intellisense on it's overload methods.CommentedJan 25, 2016 at 20:59 - Look at the method starting at line 290 in this code from my project, I'm returning json there github.com/joeaudette/cloudscribe/blob/master/src/…CommentedJan 26, 2016 at 1:07
You shouldn't have to do anything special to send back Json data. The default output formatter is already Json, and if your Startup.cs file is somewhat normal, you should have a line similar to this:
services.AddMvc();
By default, this already contains the Json formatter, and your controller should autonegotiate the return type based on what the browser asked. So a controller like the following should work (taken from this Github issue, which contains some information on why/how this work):
public class ValuesController : ApiController { public SomeClass Get() { return new SomeClass(); } public SomeClass Post([FromBody] SomeClass x) { return x; } }
- Your assuming that this Json object will always be passed to my own application and said application has an API. While your response works in that case it does not work in all cases. In this case the JSON will be either passed to an API from a third party or to a JavaScript AJAX response.CommentedJan 25, 2016 at 21:30
- Then I'm at a loss here. Why are you asking for the Json formatter, then?CommentedJan 25, 2016 at 21:40
- I sense that your question came with too much baggage. What do you need to do? Post some Json data to a third-party API? If so, then you should be using Json.Net.CommentedJan 25, 2016 at 21:42
- In this particular case it will be posted to a third-party API. Is
Json.Net
andNewtonsoft.Json
the same?CommentedJan 25, 2016 at 21:46 - @LeonardoHerrera its not sending json back, its serializing json. Matt - Json.Net is newtonsoft :)CommentedJan 25, 2016 at 22:16
config.json
file?config.json
file but looking at bothappsettings.json
andproject.json
I don't see anything that hints it is an output formatter.