I have the next Json document that I'm trying to deserialize:
{
"General": {
"Items": [
{
"fId": "divisionID",
"frmt": "Text"
},
{
"fId": "wcctOwnerID",
"frmt": "Text"
},
{
"fId": "qreID",
"frmt": "Text"
}
]
}
}
I have this classes:
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; }
}
I'm trying to deserialize with this line:
using (StreamReader r = new StreamReader(HostingEnvironment.ApplicationPhysicalPath + @"\Utils\OptionsByDB.json"))
{
var json = r.ReadToEnd();
Utils.General items = JsonConvert.DeserializeObject<Utils.General>(json);
}
But it returns null. What I'm doing wrong?
Your problem is that your JSON isn't a General
object.
Is a object that has a General
object inside it:
You need a class declaration like this:
public class JsonObject{
[JsonProperty(PropertyName = "General")]
public General rootObject {get; set;}
}
And then use:
var jsonConverted = JsonConvert.DeserializeObject<JsonObject>(json);