hanslanda5019
hanslanda5019
CC#
Created by hanslanda5019 on 3/5/2023 in #help
❔ Deserializing Json to class
I have a text file wich I save my json to but when I try to deserialize it it never works. My json that is serialized looks fine bcs it even works when I run my json through an online converter. My Library class has 1 property that is an array of Movies.
json = File.ReadAllText(FileName);
Library test = JsonConvert.DeserializeObject<Library>(json);
Debug.WriteLine(test._Movies.Length);

**Structure classes**
public class Library
{
public Movie[] _Movies { private set; get; }
public Library(Movie[] movies)
{

_Movies = movies;
}
public Library()
{
_Movies = new Movie[0];
}
}
public class Movie
{
public string _title { private set; get; }

[JsonIgnore]
public Image _Picture { private set; get; }
public string _BasePic { private set; get; }
public Movie(string title, Image picture)
{
_title = title;
_Picture = picture;
using (_Picture)
{
using (MemoryStream m = new MemoryStream())
{
_Picture.Save(m, _Picture.RawFormat);
byte[] imageBytes = m.ToArray();

// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
_BasePic = base64String;
}
}

}
}
json = File.ReadAllText(FileName);
Library test = JsonConvert.DeserializeObject<Library>(json);
Debug.WriteLine(test._Movies.Length);

**Structure classes**
public class Library
{
public Movie[] _Movies { private set; get; }
public Library(Movie[] movies)
{

_Movies = movies;
}
public Library()
{
_Movies = new Movie[0];
}
}
public class Movie
{
public string _title { private set; get; }

[JsonIgnore]
public Image _Picture { private set; get; }
public string _BasePic { private set; get; }
public Movie(string title, Image picture)
{
_title = title;
_Picture = picture;
using (_Picture)
{
using (MemoryStream m = new MemoryStream())
{
_Picture.Save(m, _Picture.RawFormat);
byte[] imageBytes = m.ToArray();

// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
_BasePic = base64String;
}
}

}
}
26 replies