Json.NET反序列化自定义对象返回null
本文关键字:返回 null 对象 自定义 NET 反序列化 Json | 更新日期: 2023-09-27 18:10:11
我在使用Json.NET将JSON字符串转换为c#对象时遇到了麻烦。
我使用AJAX调用。ashx
$.ajax({
url: "/Handler/Handler.ashx?WorkType=SaveData",
type: "POST",
data: JSON.stringify({ 'DataInfo': Info }),
//data: "{'DataInfo':" + JSON.stringify(Info) + "}",
dataType: "json",
success: function (data, textStatus, jqXHR) {
if (data.Result) {
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
}
});
Json字符串是
{
"DataInfo": [
{
"EditType": "Create",
"CustCode": "SSG",
"KeyNoStr": "rgrg",
"Requester": "rgrg",
"VerificationCode": "VAVBZ",
"Databody": "TESt123",
"HasMap": false,
"IsColse": false,
"HasOrder": false,
"IsUrgent": true
}
]
}
和我的。ashx服务器端代码像…
public class DataInfo
{
public string EditType { get; set; }
public string CustCode { get; set; }
public string KeyNoStr { get; set; }
public string Requester { get; set; }
public string VerificationCode { get; set; }
public string Databody { get; set; }
public string HasMap { get; set; }
public string IsColse { get; set; }
public string HasOrder { get; set; }
public string IsUrgent { get; set; }
}
.ashx中的main函数
public void ProcessRequest(HttpContext context)
{
Request = context.Request;
Response = context.Response;
string lv_strResult = string.Empty;
DataInfo lv_oInfo = JsonConvert.DeserializeObject<DataInfo >((new StreamReader(Request.InputStream)).ReadToEnd());
}
我做错了什么?
这是因为JSON对象是DataInfo
的数组,所以需要使用这些类进行反序列化
public class DataInfo
{
public string EditType { get; set; }
public string CustCode { get; set; }
public string KeyNoStr { get; set; }
public string Requester { get; set; }
public string VerificationCode { get; set; }
public string Databody { get; set; }
public bool HasMap { get; set; }
public bool IsColse { get; set; }
public bool HasOrder { get; set; }
public bool IsUrgent { get; set; }
}
public class RootObject
{
public List<DataInfo> DataInfo { get; set; }
}
//your method
public void ProcessRequest(HttpContext context)
{
Request = context.Request;
Response = context.Response;
string lv_strResult = string.Empty;
DataInfo lv_oInfo = JsonConvert.DeserializeObject<RootObject>((new StreamReader(Request.InputStream)).ReadToEnd());
}
您的JSON表示具有一个名为DataInfo
的类型为List<DataInfo>
的属性的结构
所以你需要用
代替DataInfo lv_oInfo = JsonConvert.DeserializeObject<DataInfo >((new StreamReader(Request.InputStream)).ReadToEnd());
var jobject = (JObject)JsonConvert.DeserializeObject((new StreamReader(Request.InputStream)).ReadToEnd());
var di_json = jobject["DataInfo"].ToString(); // Dirty but this is the main idea
var data_infos = JsonConvert.DeserializeObject<List<DataInfo>>(di_json);
由于双重反序列化,这不是世界上最好的代码,但它显示了思想