Created
October 29, 2016 22:39
-
-
Save yonixw/4210659fa292d4483a8c30a612709977 to your computer and use it in GitHub Desktop.
How to use JSON in .NET 4 and Higher with ease
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Runtime.Serialization; | |
using System.Runtime.Serialization.Json; | |
namespace Test { | |
[DataContract] | |
public class JsonStructureExample | |
{ | |
[DataMember] | |
public int id; | |
} | |
public class JsonTools { | |
private static string ToJson<T>(T data) | |
{ | |
// SO ? 1178255 | |
DataContractJsonSerializer serializer | |
= new DataContractJsonSerializer(typeof(T)); | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
serializer.WriteObject(ms, data); | |
return Encoding.UTF8.GetString(ms.ToArray()); | |
} | |
} | |
private static T FromJson<T>(string json) | |
{ | |
// https://blog.udemy.com/json-serializer-c-sharp/ | |
DataContractJsonSerializer serializer | |
= new DataContractJsonSerializer(typeof(T)); | |
using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json))) | |
{ | |
return (T)serializer.ReadObject(ms); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment