How to use System.Text.Json APIs in Asp.net - CloudFronts

How to use System.Text.Json APIs in Asp.net

Posted On November 25, 2019 by Admin Posted in 

Initially for parsing object to Json or json to object in Asp.net an additional Newtonsoft.Json Api was required, but now Microsoft has developed their own Apis “System.Test.Json”. Below Steps will guide you on how to use this api.

  1. Install the System.Text.Json NuGet package.
  2. To use the api make sure you import the following two namespaces:
    1. using System.Text.Json;
    2. using System.Text.Json.Serialization;
  3. Using the serializer as follows:
    1. The System.Text.Json serializer can read and write JSON asynchronously and is optimized for UTF-8 text, making it ideal for REST API and back-end applications.

class WeatherForecast

{

public DateTimeOffset Date {get; set;}

public int TemperatureC {get; set;}

public string Summary {get; set;}

}

 

string Serialize (WeatherForecast value)

{

return JsonSerializer.ToString<WeatherForecast>(value);

}

  1. Api also support asynchronous serialization and deserialization.

async Task SerializeAsync(WeatherForecast value, Stream stream)

{

await JsonSerializer.WriteAsync<WeatherForecast> (value, stream);

}

  1. You can also use custom attributes to control serialization behavior, for example, ignoring properties and specifying the name of the property in the JSON:

class WeatherForecast

{

public DateTimeOffset Date {get; set;}

 

// Always in Celsius.

[JsonPropertyName(“temp”)]

public int TemperatureC {get; set;}

 

public string Summary {get; set;}

 

// Don’t serialize this property.

[JsonIgnore]

public bool IsHot => TemperatureC >= 30;

}

Note: In the above point isHot property will not get parsed to json and json will look like below:

     {

“date”: “2013-01-07T00:00:00Z”,

“temp”: 23,

}


Share Story :

Secured By miniOrange