Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScriptSerializer is not allowed in .net core project?

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?

like image 543
Nivitha Gopalakrishnan Avatar asked Jan 09 '19 12:01

Nivitha Gopalakrishnan


2 Answers

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);
like image 103
Michael Ceber Avatar answered Oct 13 '22 20:10

Michael Ceber


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.

like image 12
Christos Lytras Avatar answered Oct 13 '22 18:10

Christos Lytras