Skip to content

Commit 31fe4c1

Browse files
committed
[增加]1. 增加解析帮助类
1 parent 9b305da commit 31fe4c1

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

GameFrameX.Foundation.Http.Normalization/HttpJsonResultData.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public sealed class HttpJsonResultData<T>
1111
/// 是否成功
1212
/// 表示请求是否成功执行,成功为true,失败为false。
1313
/// </summary>
14-
public bool IsSuccess { get; set; }
14+
public bool IsSuccess { get; set; } = false;
1515

1616
/// <summary>
1717
/// 数据对象
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using Newtonsoft.Json;
2+
3+
namespace GameFrameX.Foundation.Http.Normalization;
4+
5+
/// <summary>
6+
/// 提供用于处理HTTP JSON结果的辅助方法。
7+
/// </summary>
8+
public static class HttpJsonResultHelper
9+
{
10+
/// <summary>
11+
/// 将JSON字符串转换为HttpJsonResultData<T>对象。
12+
/// 该方法尝试反序列化给定的JSON字符串,并根据HTTP响应的状态码设置IsSuccess属性。
13+
/// 如果响应成功,Data属性将包含反序列化后的数据对象;否则,Data将为默认值。
14+
/// </summary>
15+
/// <typeparam name="T">要反序列化为的对象类型,必须是类并具有无参数构造函数。</typeparam>
16+
/// <param name="jsonResult">包含HTTP响应的JSON字符串。</param>
17+
/// <returns>HttpJsonResultData<T>对象,表示反序列化的结果。</returns>
18+
public static HttpJsonResultData<T> ToHttpJsonResultData<T>(this string jsonResult) where T : class, new()
19+
{
20+
HttpJsonResultData<T> resultData = new HttpJsonResultData<T>
21+
{
22+
IsSuccess = false,
23+
};
24+
try
25+
{
26+
// 反序列化JSON字符串为HttpJsonResult对象
27+
var httpJsonResult = JsonConvert.DeserializeObject<HttpJsonResult>(jsonResult);
28+
// 检查响应码是否表示成功
29+
if (httpJsonResult.Code != 0)
30+
{
31+
return resultData; // 返回默认的失败结果
32+
}
33+
34+
resultData.IsSuccess = true; // 设置成功标志
35+
// 反序列化数据部分,如果数据为空则返回类型T的默认实例
36+
resultData.Data = string.IsNullOrEmpty(httpJsonResult.Data) ? new T() : JsonConvert.DeserializeObject<T>(httpJsonResult.Data);
37+
}
38+
catch (Exception e)
39+
{
40+
// 捕获并输出异常信息
41+
Console.WriteLine(e);
42+
}
43+
44+
return resultData; // 返回结果数据
45+
}
46+
}

0 commit comments

Comments
 (0)