I have a very simple JSON file:
[
{
"smbshare": {
"name": "Backup",
"path": "\linuxserverbackup"
},
"smbshare2": {
"name": "Tools",
"path": "\linuxservertools"
}
}
]
My model class:
public class SmbShare
{
[JsonProperty("name")]
public string Name { get;set; }
[JsonProperty("path")]
public string Path { get; set; }
}
And the SmbController
public class SmbController : Controller
{
public ActionResult Index()
{
using (StreamReader r = new StreamReader("smbshares.json"))
{
string json = r.ReadToEnd();
List<SmbShare> items = JsonConvert.DeserializeObject<List<SmbShare>>(json);
}
}
}
The list items
contains only one object but with empty values (null / 0).
Any hints why the mapping doesn’t work?
3
Answers
The class doesn’t match your JSON. You’re deserializing an array of one object with two properties,
smbshare
andsmbshare2
. The serializer doesn’t know that you intend these to be array elements. To get the result you expect, you will have to use a custom JsonConverter to achieve the desired behaviour.You have a mismatch between your JSON and your data structure:
List<SmbShare>
would be represented in JSON as follows:You need to either update your JSON file or your data structure.
Your JSON does not represent
List<SmbShare>
, but a list of objects containingSmbShare
properties. One way to handle this is to useDictionary<string, SmbShare>
(otherwise you will need to have a class withsmbshare
andsmbshare2
properties):Or if you can – just fix the JSON to:
Then it will be deserialized to
List<SmbShare>
correctly.