c# - 从 JsonConvert 反序列化 JSON 对象返回 null
问题描述
无需序列化从 API 响应中获取数据
var apiResponseDetails = authorityApiResponse.Content.ReadAsStringAsync().Result;
"[
{
\"<RoleName>k__BackingField\":\"L5 _Admin _Role\",
\"<RoleType>k__BackingField\":\"565,1\"
}
]"
在反序列化相同的响应时,对于RoleName
和RoleType
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);
}
解决方案
我认为这不是一个合适的解决方案,因为添加了[JsonObject]
属性而不是[Serializable]
. 问题k__BackingField
和null
解决了。如果有人确切地知道如何通过添加来处理这个问题,[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__BackingField
都null
消失
[Serializable, DataContract]
public class ChangeRoleNotification
{
[DataMember]
public string RoleName { get; set; }
[DataMember]
public string RoleType { get; set; }
}
通过仅在方法 II 中解决的服务器端添加[DataContract]
类和属性,我相信这是最合适的[DataMember]
推荐阅读
- android - Searchview 过滤器不适用于包含已解析 JSON 的列表,但适用于非 JSON 列表
- php - PDO:使用子字符串作为标准来获取行数
- python - 在 EMR 中运行 Jupyter notebook 时没有名为“pyspark”的模块
- python - 使用 Python 将 Excel DATE(不是日期时间)数据插入 SQL Server
- java - Maven发布插件配置及示例
- java - 如何在 swagger 模型中创建嵌套对象
- c++ - 如何让用户等待才能再次使用某个功能?
- scala - 将 Akka HTTP 重定向到 HTTPS
- haskell - 从generics-sop的ConstructorInfo中提取嵌套类型信息
- mysql - 如何正确地将 mysql-query-results 解析为 typescript 对象