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?
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);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With