简体   繁体   中英

Serialize/deserialize without external library in c#

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());
        }
    }
}``` 

System.Text.Json作为 Microsoft 和外部序列化程序朋友Newtonsoft.Json的库。

Dotnet has a library for your request Source page

string jsonString = JsonSerializer.Serialize(weatherForecast);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM