Home > Software engineering >  Serialize/deserialize without external library in c#
Serialize/deserialize without external library in c#

Time:06-15

How do i serialize/de serialize JSON data in c# without using any library or nugget package

i tried this it allways shows me error!

{
    /// <summary>
    /// Deserialize an from json string
    /// </summary>
    public static T Deserialize<T>(string body)
    {
        using (var stream = new MemoryStream())
        using (var writer = new StreamWriter(stream))
        {
            writer.Write(body);
            writer.Flush();
            stream.Position = 0;
            return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(stream);
        }
    }

    /// <summary>
    /// Serialize an object to json
    /// </summary>
    public static string Serialize<T>(T item)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            new DataContractJsonSerializer(typeof(T)).WriteObject(ms, item);
            return Encoding.Default.GetString(ms.ToArray());
        }
    }
}``` 

CodePudding user response:

System.Text.Json as a library from Microsoft and Newtonsoft.Json, an external serializer friend.

CodePudding user response:

Dotnet has a library for your request Source page

string jsonString = JsonSerializer.Serialize(weatherForecast);

var weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString);
  • Related