11#if ! USELIGHTWEIGHTJSONPARSER
22
33using System ;
4+ using System . Net . Http ;
5+ using System . Text . Json ;
46using System . Text . Json . Nodes ;
5-
67using System . Text . Json . Serialization . Metadata ;
8+ using System . Threading ;
9+ using System . Threading . Tasks ;
10+ using Microsoft . Extensions . Logging ;
711
812namespace Hi3Helper . Plugin . Core . Utility . Json ;
913
@@ -73,6 +77,37 @@ public static void SetConfigValueIfEmpty<T>(this JsonObject obj, string property
7377 obj . SetConfigValue ( propertyName , value , typeInfo ) ;
7478 }
7579 }
80+
81+ public static Task < T > GetApiResponseFromJsonAsync < T> ( this HttpClient client ,
82+ string url ,
83+ JsonTypeInfo < T ? > typeInfo ,
84+ CancellationToken token = default )
85+ => client . GetApiResponseFromJsonAsync ( url , typeInfo , null , token ) ;
86+
87+ public static async Task < T > GetApiResponseFromJsonAsync < T> ( this HttpClient client ,
88+ string url ,
89+ JsonTypeInfo < T ? > typeInfo ,
90+ HttpMethod ? httpMethod = null ,
91+ CancellationToken token = default )
92+ {
93+ httpMethod ??= HttpMethod . Get ;
94+
95+ using HttpRequestMessage request = new ( httpMethod , url ) ;
96+ using HttpResponseMessage response =
97+ await client . SendAsync ( request , HttpCompletionOption . ResponseHeadersRead , token ) ;
98+
99+ response . EnsureSuccessStatusCode ( ) ;
100+
101+ #if DEBUG
102+ string jsonResponse = await response . Content . ReadAsStringAsync ( token ) ;
103+ SharedStatic . InstanceLogger . LogTrace ( "API response for <T> ({TypeOf}): {JsonResponse}" , typeof ( T ) . Name , jsonResponse ) ;
104+ return JsonSerializer . Deserialize ( jsonResponse , typeInfo )
105+ ?? throw new NullReferenceException ( $ "API response for <T> ({ typeof ( T ) . Name } ) Returns null response!") ;
106+ #else
107+ return await response . Content . ReadFromJsonAsync ( typeInfo , token )
108+ ?? throw new NullReferenceException ( $ "API response for <T> ({ typeof ( T ) . Name } ) Returns null response!") ;
109+ #endif
110+ }
76111}
77112
78113#endif
0 commit comments