Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading