eomer
eomer

Reputation: 3574

How to convert json file to List<MyClass>

I am trying to create a log file in json format from a List. my class for list is

public class ChunkItem
    {
        public int start { get; set; }
        public int end { get; set; }
    }
 public class DownloadItem
    {
        public int id { get; set; }
        public string fname { get; set; }
        public string downloadPath { get; set; }
        public int chunkCount { get; set; }
        public ChunkItem[] chunks { get; set; }
        public DownloadItem(int _id, string _fname, string _downloadPath, int _chunkCount, ChunkItem[] _chunks)
        {
            id = _id;
            fname = _fname;
            downloadPath = _downloadPath;
            chunkCount = _chunkCount;
            chunks = _chunks;
        }

    }

creating a json file from this class works fine

ChunkItem[] chunks = new ChunkItem[2];
chunks[0] = new ChunkItem();
chunks[0].start = 0;
chunks[0].end = 0;
chunks[1] = new ChunkItem();
chunks[1].start = 0;
chunks[1].end = 0;
List<DownloadItem> lst = new List<DownloadItem>();
lst.Add(new DownloadItem(0, "", "", 2, chunks));
lst.Add(new DownloadItem(1, "aaa", "sss", 2, chunks));
lst.Add(new DownloadItem(2, "bbb", "ddd", 2, chunks));
string json = JsonConvert.SerializeObject(lst);
System.IO.File.WriteAllText(logPath, json);

I want to read the file to same class list and do some updates or add new lines I can read the file to a string but cannot create a new list how can I convert string (read json file) to List<DownloadItem> new list

Upvotes: 0

Views: 328

Answers (3)

dhrumil shah
dhrumil shah

Reputation: 82

I use Newtonsoft, where creating the instances and filling them is simple

var result = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(jsonString);

Upvotes: 0

Alexander Powolozki
Alexander Powolozki

Reputation: 675

Clas DownloadItem is missing a default parameterless constructor.

Upvotes: 0

Anu Viswan
Anu Viswan

Reputation: 18155

You need to read all the contends from the file and deserialize the json string to List<DownloadItem>

var jsonData = File.ReadAllText(filePath)
var list = JsonConvert.DeserializeObject<List<DownloadItem>>(jsonData);

Upvotes: 1

Related Questions