skip to Main Content

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


  1. The class doesn’t match your JSON. You’re deserializing an array of one object with two properties, smbshare and smbshare2. 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.

    Login or Signup to reply.
  2. You have a mismatch between your JSON and your data structure:

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

    [
      {
        "name": "Backup",
        "path": "\linuxserverbackup"
      },
      {
        "name": "Tools",
        "path": "\linuxservertools"
      }
    ]
    

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

    Login or Signup to reply.
  3. Your JSON does not represent List<SmbShare>, but a list of objects containing SmbShare properties. One way to handle this is to use Dictionary<string, SmbShare> (otherwise you will need to have a class with smbshare and smbshare2 properties):

    var json = """
    [
      {
        "smbshare": {
          "name": "Backup",
          "path": "\linuxserverbackup"
        },
        "smbshare2": {
          "name": "Tools",
          "path": "\linuxservertools"
        }
      }
    ]
    """;
    
    var list = JsonConvert.DeserializeObject<List<Dictionary<string, SmbShare>>>(json);
    Console.WriteLine(list.First().First().Value.Name); // Prints "Backup"
    

    Or if you can – just fix the JSON to:

    [
      {
          "name": "Backup",
          "path": "\linuxserverbackup"
      },
      {
          "name": "Tools",
          "path": "\linuxservertools"
      }
    ]
    

    Then it will be deserialized to List<SmbShare> correctly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search