首页 > 解决方案 > 从 JsonConvert 反序列化 JSON 对象返回 null

问题描述

无需序列化从 API 响应中获取数据

var apiResponseDetails = authorityApiResponse.Content.ReadAsStringAsync().Result;
"[
    {
        \"<RoleName>k__BackingField\":\"L5 _Admin _Role\",
        \"<RoleType>k__BackingField\":\"565,1\"
    }
]"

在反序列化相同的响应时,对于RoleNameRoleType

lstRole = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChangeRoleNotification>>(Convert.ToString(apiResponseDetails));
Name                Value                               
lstRole             Count = 1                           
    [0]             {Presentation.Common.ChangeRoleNotification}    
       RoleName     null                                            
       RoleType     null

[Serializable]
public class ChangeRoleNotification
{
    [Newtonsoft.Json.JsonProperty(PropertyName = "RoleName")]
    public string RoleName { get; set; }
    [Newtonsoft.Json.JsonProperty(PropertyName = "RoleType")]
    public string RoleType { get; set; }
}
...

GetUserRolesDetailsRequest getUserRolesDetails = new GetUserRolesDetailsRequest();
getUserRolesDetails.UserID = objUser.UserId;
getUserRolesDetails.RoleName = HttpContext.Current.Session["UserTypeName"].ToString();
getUserRolesDetails.RoleType = HttpContext.Current.Session["RoleType"].ToString();
getUserRolesDetails.RoleID = Convert.ToInt64(HttpContext.Current.Session["RoleID"]);
    
System.Net.Http.HttpResponseMessage authorityApiResponse = new System.Net.Http.HttpResponseMessage(false ? HttpStatusCode.OK : HttpStatusCode.BadRequest);
System.Net.Http.HttpContent RequestDetails = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(getUserRolesDetails), Encoding.UTF8);

if (!String.IsNullOrEmpty(GetWebConfigKeyValueStatic("FrameworkApiURL")))
{
    authorityApiResponse = API.PostAPIAsJson($"{GetWebConfigKeyValueStatic("FrameworkApiURL")}Category/GetCategoryUserRolesDetails", RequestDetails);
    if (authorityApiResponse != null && authorityApiResponse.StatusCode == HttpStatusCode.OK && authorityApiResponse.Content.ReadAsStringAsync().Result != null)
    {
        var apiResponseDetails = authorityApiResponse.Content.ReadAsStringAsync().Result;
        lstRole = new List<ChangeRoleNotification>();
        lstRole = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChangeRoleNotification>>(Convert.ToString(apiResponseDetails));
    }
}

由于我正在将项目转换为 ASP.NET MVC 3-Tier,所以我看到了一个奇怪的k__BackingField意思是什么?


更新了响应 API 的服务器端片段:

[Route("Category/GetCategoryUserRolesDetails")]
[ActionName("GetCategoryUserRolesDetails")]
[HttpPost]
public HttpResponseMessage GetCategoryUserRolesDetails(CategoryRequestDetails categoryRequestDetails)
{
    List<ChangeRoleNotification> response = null;
    FrameworkAPIs.Log.LogClass.log.Debug("\nModule Name : Category;\nMethod Name : GetCategoryUserRolesDetails;\n Message :GetCategoryUserRolesDetails method starts ");
    string statusCode = String.Empty;
    DateTime StartTime = DateTime.Now;
    DateTime EndTime = DateTime.Now;
    Int64 WebServiceLogID = (new ServiceLogGenerator()).GenerateLog(categoryRequestDetails, "Category", "GetCategoryUserRolesDetails", StartTime, EndTime, "", "", null, 0);
    try
    {
        ManageCategory mangageCategory = new ManageCategory();
        if (categoryRequestDetails.UserID > 0)
            response = mangageCategory.GetCategoryUserRolesDetails(categoryRequestDetails);
        else
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid UserID");
    }
    catch (Exception ex)
    {
        FrameworkAPIs.Log.LogClass.log.Error("\nModule Name : Category;\nMethod Name : GetCategoryUserRolesDetails;\nError Message : " + ex.Message + ex.StackTrace + "\n");
        (new ServiceLogGenerator()).GenerateLog(null, "", "", StartTime, DateTime.Now, ex.StackTrace + ";\n" + ex.Message, "", null, WebServiceLogID);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
    }
    (new ServiceLogGenerator()).GenerateLog(null, "", "", StartTime, DateTime.Now, "", "", response, WebServiceLogID);
    FrameworkAPIs.Log.LogClass.log.Debug("\nModule Name : Category;\nMethod Name : GetCategoryUserRolesDetails;\n Message :GetCategoryUserRolesDetails method ends\nResult :" + response);
    return Request.CreateResponse<List<ChangeRoleNotification>>(HttpStatusCode.OK, response);
}

标签: c#jsonjson.netdeserializationjson-deserialization

解决方案


我认为这不是一个合适的解决方案,因为添加了[JsonObject]属性而不是[Serializable]. 问题k__BackingFieldnull解决了。如果有人确切地知道如何通过添加来处理这个问题,[Serializable]那么他们总是受欢迎的

[Newtonsoft.Json.JsonObject]
public class ChangeRoleNotification
{
    public string RoleName { get; set; }
    public string RoleType { get; set; }
}

使用以下方法更新

方法一: k__BackingField消失。但null似乎坚持在服务器端

[Serializable]
public class ChangeRoleNotification
{
    private string RoleNameField;
    public string RoleName
    {
        get { return RoleNameField; }
        set { RoleNameField = value; }
    }
    private string RoleTypeField;
    public string RoleType
    {
        get { return RoleTypeField; }
        set { RoleTypeField = value; }
    }
}

方法二(有效):两者k__BackingFieldnull消失

[Serializable, DataContract]
public class ChangeRoleNotification
{
  [DataMember]
  public string RoleName { get; set; }

  [DataMember]
  public string RoleType { get; set; }
}

通过仅在方法 II 中解决的服务器端添加[DataContract]类和属性,我相信这是最合适的[DataMember]


推荐阅读