c# - 无法将 json 字符串反序列化为类
问题描述
我在.net 中有一个类库项目。我不能使用第 3 方程序集,只允许使用 Microsoft 程序集。
我有一个来自 Web API 的返回类,如下所示。我尝试将字符串反序列化为此类,但它不起作用,但它适用于其他类。我认为问题在于接受“T”类。
我的课;
public class ApiResponse<T>
{
public T Value { get; set; }
public bool HasError { get; set; }
public string ErrorMessage { get; set; }
public string DetailedErrorMessage { get; set; }
public string ErrorCode { get; set; }
public ApiResponse(string errorCode, string errorMessage, string detailedErrorMessage = "")
{
this.ErrorMessage = errorMessage;
this.ErrorCode = errorCode;
this.HasError = true;
this.DetailedErrorMessage = detailedErrorMessage;
}
public ApiResponse(T value)
{
this.Value = value;
this.HasError = false;
ErrorMessage = string.Empty;
}
public ApiResponse()
{
this.HasError = false;
ErrorMessage = string.Empty;
}
public ApiResponse(OLException e)
{
ErrorCode = e.ErrorCode;
ErrorMessage = e.Message;
HasError = true;
DetailedErrorMessage = e.StackTrace;
}
public ApiResponse(Exception e)
{
ErrorMessage = e.Message;
HasError = true;
DetailedErrorMessage = e.StackTrace;
}
}
这是我的反序列化功能。
private T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
这是我如何使用以下方法
ApiResponse<bool> response = JsonDeserialize<ApiResponse<bool>>(responseString);
响应字符串 -->
{"value":false,"hasError":true,"errorMessage":"user1 客户端已经存在。","detailedErrorMessage":"","errorCode":null}
没有错误只是响应类在反序列化后似乎为空,但如您所见,响应字符串有一些值。
解决方案
您已经引用了System.Text.Json
(Microsoft),因此您可以这样做:
static T DeserializeEasyWay<T>(string input)
{
return JsonSerializer.Deserialize<T>(input,
new JsonSerializerOptions{PropertyNameCaseInsensitive = true});
}
我用你的字符串测试过。有用。
推荐阅读
- c3.js - c3.js 删除时间序列之间不连续天数的空格
- javascript - 使用 Webpack 设置延迟加载组件的正确路径 - ES6
- angularjs - angularjs - 从控制器更新 ng-model 值?
- ansible - Ansible Inventory 中主机之间的暂停时间
- c - 如何在我的自研操作系统中控制显卡?
- android - 使用 JobService 启动 Service 的正确方法
- clojure - 如何让两个 Datomic Cloud 客户端保持同步?
- javascript - 在 Javascript 类中使用 const
- gradle - 将 liquibase 参数传递给 gradle liquibase 'update' 任务
- c++ - 在异步 60 秒延迟后在 C++ 中执行函数?