I would like to deserialize this json file. The json file has the following pattern that repeats itself:
{
"Province": {
"District": {
"Sector": {
"Cell": [
"Village1",
"Village2",
"Village3",
"Village4"
]
}
}
}
}
I am using the following code to read and deserialized the json
using System;
using System.Collections.Generic;
using System.Text.Json;
class Program
{
public class Province {
public string Name { get; set; }
public ICollection<District> Districts { get; set; }
}
public class District {
public string Name { get; set; }
public ICollection<Sector> Sectors { get; set; }
}
public class Sector {
public string Name { get; set; }
public ICollection<Cell> Cells { get; set; }
}
public class Cell {
public string Name { get; set; }
public ICollection<Village> Villages { get; set; }
}
public class Village {
public string Name { get; set; }
}
static void Main(string[] args) {
string json = DownloadJsonData();
var provinces = JsonSerializer.Deserialize<List<Province>>(json);
Console.WriteLine(provinces[0].Name);
}
private static string DownloadJsonData() {
using var webClient = new System.Net.WebClient();
string result = webClient.DownloadString("https://raw.githubusercontent.com/ngabovictor/Rwanda/master/data.json");
return result;
}
}
The above code results in the following exception
HResult=0x80131500 Message=The JSON value could not be converted to System.Collections.Generic.List`1[Program+Province]. Path: $ | LineNumber: 0 | BytePositionInLine: 1. Source=System.Text.Json
What I am doing wrong?
{, so it's an object, not a list, thus why you get that specific exception. In addition. Sector.Cell should be a string collection, not a collection ofCell.