39

I am working in .net core project. I want to serialize the objects using JavaScriptSerializer.

JavaScriptSerializer Serializer = new JavaScriptSerializer();

I added the namespace using System.Web.Script.Serialization;. It throws errors. I googled it. I saw like .net core project does not have System.Web.Script.Serialization; in some sites.

Is there have any another way to serialize the objects in the .net core like JavaScriptSerializer?

3 Answers3

58

In .net core the most common way of serializing and deserializing objects (JSON) using Newtonsoft.Json.

You need to install the Nuget Package of Newtonsoft.Json

add using a statement like:

using Newtonsoft.Json;

and use it as:

object o = JsonConvert.DeserializeObject(json1);
string json2 = JsonConvert.SerializeObject(o, Formatting.Indented);
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Michael Ceber
  • 2,304
  • 1
  • 11
  • 14
  • How-to convert string (format json) to List: `{"result":["PRE_VPN_Usuarios","PRE_Usuarios COMUNICADOS MAD","PRE_Campaña Agentes MAD"]}` – Kiquenet Sep 19 '22 at 10:54
20

For ASP.NET Core 3.1 we can use JsonSerializer.Deserialize from System.Text.Json with a string/dynamic dictionary Dictionary<string, dynamic>.

Example loading ClientApp\package.json:

using System;
using System.Text.Json;
using System.Collections.Generic;

...

var packageJson = File.ReadAllText(Path.Combine(env.ContentRootPath, "ClientApp", "package.json"));

var packageInfo = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(packageJson);

Console.WriteLine("SPA Name: {0}, SPA Version: {1}", 
    packageInfo["name"], packageInfo["version"]);

Of course we'll have to copy ClientApp\package.json to the publish directory using a Target > Copy command inside .csproj.

Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
  • this almost works, but nested elements are of type `JsonElement` instead of `Dictionary` and can't be indexed by strings. – Dave Cousineau Mar 07 '23 at 17:36
  • @DaveCousineau indeed, good point; this is mostly for quick access to flat level properties; for more complex cases and when we need to access nested elements, I believe it's better to create a proper interface/class and use that as a generic for the deserializer. – Christos Lytras Mar 07 '23 at 18:16
4

Install Newtonsoft.Json and then

in Controller:

string data = JsonConvert.SerializeObject(new { MyUser = user, MyId = id });
object dataObj = JsonConvert.DeserializeObject(data);
return Json(dataObj);

and in Javascript file:

$.ajax({
   // some codes!
   success: function(data){
      var user = data.MyUser;
      var id = data.MyId
   }
});
x19
  • 8,277
  • 15
  • 68
  • 126