Search code examples
c#jsonjson.net

Newtonsoft.Json DeserializeObject not working


I have a very simple JSON file:

[
  {
    "smbshare": {
      "name": "Backup",
      "path": "\\linuxserver\backup"
    },
    "smbshare2": {
      "name": "Tools",
      "path": "\\linuxserver\tools"
    }
  }
]

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?


Solution

  • You have a mismatch between your JSON and your data structure:

    List<SmbShare> would be represented in JSON as follows:

    [
      {
        "name": "Backup",
        "path": "\\linuxserver\backup"
      },
      {
        "name": "Tools",
        "path": "\\linuxserver\tools"
      }
    ]
    

    You need to either update your JSON file or your data structure.