45

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 Answers 3

66

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);
Sign up to request clarification or add additional context in comments.

1 Comment

How-to convert string (format json) to List<string>: {"result":["PRE_VPN_Usuarios","PRE_Usuarios COMUNICADOS MAD","PRE_Campaña Agentes MAD"]}
21

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.

2 Comments

this almost works, but nested elements are of type JsonElement instead of Dictionary<string, dynamic> and can't be indexed by strings.
@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.
5

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
   }
});

1 Comment

What is Json(dataObj) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.