JsonConvert.DeserializeObject returns ActionResult 方法中为空
JsonConvert.DeserializeObject returns null in ActionResult Method
我有下一个要反序列化的 Json 文档:
{
"General": {
"Items": [
{
"fId": "divisionID",
"frmt": "Text"
},
{
"fId": "wcctOwnerID",
"frmt": "Text"
},
{
"fId": "qreID",
"frmt": "Text"
}
]
}
}
我有这个类:
public class Item
{
[JsonProperty(PropertyName = "fId")]
public string fId { get; set; }
[JsonProperty(PropertyName = "frmt")]
public string frmt { get; set; }
}
public class General
{
[JsonProperty(PropertyName = "Items")]
public List<Item> Items { get; set; }
}
我正在尝试用这一行反序列化:
using (StreamReader r = new StreamReader(HostingEnvironment.ApplicationPhysicalPath + @"\Utils\OptionsByDB.json"))
{
var json = r.ReadToEnd();
Utils.General items = JsonConvert.DeserializeObject<Utils.General>(json);
}
但它 returns 无效。我做错了什么?
您的问题是您的 JSON 不是 General
对象。
是一个有一个General
对象的对象:
您需要这样的 class 声明:
public class JsonObject{
[JsonProperty(PropertyName = "General")]
public General rootObject {get; set;}
}
然后使用:
var jsonConverted = JsonConvert.DeserializeObject<JsonObject>(json);
我有下一个要反序列化的 Json 文档:
{
"General": {
"Items": [
{
"fId": "divisionID",
"frmt": "Text"
},
{
"fId": "wcctOwnerID",
"frmt": "Text"
},
{
"fId": "qreID",
"frmt": "Text"
}
]
}
}
我有这个类:
public class Item
{
[JsonProperty(PropertyName = "fId")]
public string fId { get; set; }
[JsonProperty(PropertyName = "frmt")]
public string frmt { get; set; }
}
public class General
{
[JsonProperty(PropertyName = "Items")]
public List<Item> Items { get; set; }
}
我正在尝试用这一行反序列化:
using (StreamReader r = new StreamReader(HostingEnvironment.ApplicationPhysicalPath + @"\Utils\OptionsByDB.json"))
{
var json = r.ReadToEnd();
Utils.General items = JsonConvert.DeserializeObject<Utils.General>(json);
}
但它 returns 无效。我做错了什么?
您的问题是您的 JSON 不是 General
对象。
是一个有一个General
对象的对象:
您需要这样的 class 声明:
public class JsonObject{
[JsonProperty(PropertyName = "General")]
public General rootObject {get; set;}
}
然后使用:
var jsonConverted = JsonConvert.DeserializeObject<JsonObject>(json);