Created
September 25, 2018 10:19
-
-
Save rozputnii/3ae982e0ff4cfd4ba8db1f7df34eed29 to your computer and use it in GitHub Desktop.
.Net Standart. JsonExtensions for serialize/deserialize any types
This file contains hidden or 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
| public static class JsonExtensions | |
| { | |
| private static readonly JsonSerializer JsonSerializer = JsonSerializer.CreateDefault(); | |
| /// <summary> | |
| /// Serializes the specified instance and writes the JSON structure | |
| /// </summary> | |
| /// <param name="value">The value of <typeparam name="T"></typeparam> to serialize.</param> | |
| /// <typeparam name="T">The type of the object to serialize.</typeparam> | |
| public static string ToJson<T>(this T value) | |
| { | |
| if (value == null) | |
| return default; | |
| using (var stringWriter = new StringWriter(new StringBuilder(512), CultureInfo.InvariantCulture)) | |
| using (var jsonTextWriter = new JsonTextWriter(stringWriter)) { | |
| JsonSerializer.Serialize(jsonTextWriter, value, typeof(T)); | |
| return stringWriter.ToString(); | |
| } | |
| } | |
| /// <summary> | |
| /// Deserializes the JSON structure contained into an instance of the specified type. | |
| /// </summary> | |
| /// <typeparam name="T">The type of the object to deserialize.</typeparam> | |
| /// <returns>The instance of <typeparamref name="T" /> being deserialized.</returns> | |
| /// <example>"{"property":"value"}"</example> | |
| public static T FromJson<T>(this string json) | |
| { | |
| if (string.IsNullOrWhiteSpace(json)) | |
| return default; | |
| using (var stringReader = new StringReader(json)) | |
| using (var jsonTextReader = new JsonTextReader(stringReader)) { | |
| try { | |
| return JsonSerializer.Deserialize<T>(jsonTextReader); | |
| } | |
| catch { | |
| return default; | |
| } | |
| } | |
| } | |
| /// <summary> | |
| /// Deserializes the JSON structure from <see cref="Stream" /> into an instance of the specified type. | |
| /// </summary> | |
| /// <param name="stream">The <see cref="Stream" /> containing the object.</param> | |
| /// <typeparam name="T">The type of the object to deserialize.</typeparam> | |
| /// <returns>The instance of <typeparamref name="T" /> being deserialized.</returns> | |
| public static T FromJsonStream<T>(this Stream stream) | |
| { | |
| if (!stream?.CanRead ?? true) | |
| return default; | |
| using (var streamReader = new StreamReader(stream)) | |
| using (var jsonTextReader = new JsonTextReader(streamReader)) { | |
| try { | |
| return JsonSerializer.Deserialize<T>(jsonTextReader); | |
| } | |
| catch { | |
| return default; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment