WGet.NET 4.4.1
A WinGet wrapper library for .Net.
Loading...
Searching...
No Matches
JsonHelper.cs
1//--------------------------------------------------//
2// Created by basicx-StrgV //
3// https://github.com/basicx-StrgV/ //
4//--------------------------------------------------//
5using System;
6#if NETCOREAPP3_1_OR_GREATER
7using System.IO;
8using System.Text;
9using System.Text.Json;
10using System.Threading;
11using System.Threading.Tasks;
12#elif NETSTANDARD2_0
13using Newtonsoft.Json;
14#endif
16
17namespace WGetNET.Helper
18{
23 internal static class JsonHelper
24 {
40 public static T StringToObject<T>(string jsonString) where T : class
41 {
42 T? instance = null;
43
44 try
45 {
46#if NETCOREAPP3_1_OR_GREATER
47 instance = JsonSerializer.Deserialize<T>(jsonString);
48#elif NETSTANDARD2_0
49 instance = JsonConvert.DeserializeObject<T>(jsonString);
50#endif
51 }
52 catch (Exception e)
53 {
54 throw new InvalidJsonException(e);
55 }
56
57 if (instance == null)
58 {
59 throw new InvalidJsonException();
60 }
61
62 return instance;
63 }
64
65#if NETCOREAPP3_1_OR_GREATER
85 public static async Task<T> StringToObjectAsync<T>(string jsonString, CancellationToken cancellationToken = default) where T : class
86 {
87 T? instance = null;
88
89 try
90 {
91 using MemoryStream dataStream = new(Encoding.UTF8.GetBytes(jsonString));
92
93 instance = await JsonSerializer.DeserializeAsync<T>(dataStream, null, cancellationToken);
94 }
95 catch (Exception e)
96 {
97 throw new InvalidJsonException(e);
98 }
99
100 if (instance == null)
101 {
102 throw new InvalidJsonException();
103 }
104
105 return instance;
106 }
107#endif
108
116 public static string GetJson(object input)
117 {
118 string json = string.Empty;
119
120#if NETCOREAPP3_1_OR_GREATER
121 json = JsonSerializer.Serialize(input);
122#elif NETSTANDARD2_0
123 json = JsonConvert.SerializeObject(input);
124#endif
125
126 return json;
127 }
128 }
129}
Exception that gets thrown if the provided json string could not be deserialized.