Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Newtonsoft deserialize JSON array

I'm trying to deserialize an array using Newtonsoft so i can display files from a cloud based server in a listbox but i always end up getting this error no matter what i try:

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Path '[0].priv', line 4, position 15.'

Thisis an example try to deserialize:

[
 {
  "code": 200,
  "priv": [
     {
        "file": "file.txt",
        "ext": "txt",
        "size": "104.86"
     },
     {
        "file": "file2.exe",
        "ext": "exe",
        "size": "173.74"
     },

  ],
  "pub": [
     {
        "file": "file.txt",
        "ext": "txt",
        "size": "104.86"
     },
     {
        "file": "file2.exe",
        "ext": "exe",
        "size": "173.74"
     }
  ]
 }
]

I tried using a C# Class like this:

    public class ListJson
{
    [JsonProperty("pub")]
    public List List { get; set; }
}

public class List
{
    [JsonProperty("file")]
    public string File { get; set; }

    [JsonProperty("ext")]
    public string Ext { get; set; }

    [JsonProperty("size")]
    public string Size { get; set; }
}
    [JsonProperty("priv")]
public List List { get; set; }
}

public class List
{
    [JsonProperty("file")]
    public string File { get; set; }

    [JsonProperty("ext")]
    public string Ext { get; set; }

    [JsonProperty("size")]
    public string Size { get; set; }
}

And deserialize with:

List<list> fetch = Newtonsoft.Json.JsonConvert.DeserializeObject<List<list>>(json);
like image 863
Zeq Avatar asked May 16 '17 21:05

Zeq


1 Answers

The correct C# class structure for your JSON is the following:

public class FileEntry
{
    public string file { get; set; }
    public string ext { get; set; }
    public string size { get; set; }
}

public class FileList
{
    public int code { get; set; }
    public List<FileEntry> priv { get; set; }
    public List<FileEntry> pub { get; set; }
}

Deserializing it in this way:

var fetch = JsonConvert.DeserializeObject<FileList[]>(json);
var fileList = fetch.First(); // here we have a single FileList object

As said in the other answer, creating a class called List doesn't automagically turn it into a collection of objects. You need to declare the types to be deserialized from an array a collection type (e.g. List<T>, T[], etc.).

Small tip: when in doubt, use json2csharp.com to generate strongly typed classes from a json string.

like image 159
Federico Dipuma Avatar answered Oct 10 '22 00:10

Federico Dipuma