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

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

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 :

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close