首页 > 解决方案 > 无法将 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}

没有错误只是响应类在反序列化后似乎为空,但如您所见,响应字符串有一些值。

在此处输入图像描述

标签: c#.netjson

解决方案


您已经引用了System.Text.Json(Microsoft),因此您可以这样做:

static T DeserializeEasyWay<T>(string input)
{
    return JsonSerializer.Deserialize<T>(input, 
        new JsonSerializerOptions{PropertyNameCaseInsensitive = true});
}

我用你的字符串测试过。有用。


推荐阅读