152

Since there is no JavaScriptSerializer, what native implementation can be used to handle this?

I noticed JsonResult and I can format data to JSON with this, but how do I deserialize?

Or maybe I am missing some dependencies in project.json?

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
Jakub Wisniewski
  • 2,189
  • 4
  • 20
  • 34

2 Answers2

257

You can use Newtonsoft.Json, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding which is a dependency of Microsoft.AspNet.Mvc. So, you don't need to add a dependency in your project.json.

#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);

Note, using a WebAPI controller you don't need to deal with JSON.

UPDATE ASP.Net Core 3.0

Json.NET has been removed from the ASP.NET Core 3.0 shared framework.

You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader and Utf8JsonWriter. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.

To get started, use the JsonSerializer class in the System.Text.Json.Serialization namespace. See the documentation for information and samples.

To use Json.NET in an ASP.NET Core 3.0 project:

    services.AddMvc()
        .AddNewtonsoftJson();

Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.

patridge
  • 26,385
  • 18
  • 89
  • 135
agua from mars
  • 16,428
  • 4
  • 61
  • 70
  • Now AspNetCore.Mcv has no dependencies on Newtonsoft.JSON . Microsoft.AspNet.Mvc.Formatters.Json assembly used for serialization. – Roman Pokrovskij Nov 16 '16 at 07:31
  • 9
    @RomanPokrovskij, wrong, : `Microsoft.AspNetCore.Mvc.Formatters.Json` has a dependency to `Microsoft.AspNetCore.JsonPatch` which has a dependency to `Newtonsoft.Json` 9.0.1 https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.Formatters.Json/, https://www.nuget.org/packages/Microsoft.AspNetCore.JsonPatch/ – agua from mars Nov 16 '16 at 11:09
  • You can also use JsonConvert.DeserializeObject(json) to deserialize to an specific class. – Nuno Ribeiro Mar 22 '19 at 11:25
45

.net core

using System.Text.Json;

###To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

###Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft site

jutky
  • 3,895
  • 6
  • 31
  • 45
NoloMokgosi
  • 1,678
  • 16
  • 10