Casting Error, Not sure why. Newtonsoft.Json;

using System;
using Newtonsoft.Json;

namespace Cereal
{
public class Program
{
public static void Main(string[] args)
{
// Person p = new Person{
// First = "John",
// Middle = "Doodle",
// Last = "Doe",
// Age = 23
// };

// var r = p.Serialize("test.json");
// Console.WriteLine($"{r}");

Person np = Serializer.Deserialize<Person>("test.json");
Console.WriteLine($"{np}");

}
}
}

// This is in the Serializer class
public static T Deserialize<T>(string filePath)
{
string content;

using (StreamReader sr = new(filePath))
{
content = sr.ReadToEnd();
}

var settings = GetJsonSettings();
Console.WriteLine($"{content}");
return (T)JsonConvert.DeserializeObject<T>(content, settings);
}
using System;
using Newtonsoft.Json;

namespace Cereal
{
public class Program
{
public static void Main(string[] args)
{
// Person p = new Person{
// First = "John",
// Middle = "Doodle",
// Last = "Doe",
// Age = 23
// };

// var r = p.Serialize("test.json");
// Console.WriteLine($"{r}");

Person np = Serializer.Deserialize<Person>("test.json");
Console.WriteLine($"{np}");

}
}
}

// This is in the Serializer class
public static T Deserialize<T>(string filePath)
{
string content;

using (StreamReader sr = new(filePath))
{
content = sr.ReadToEnd();
}

var settings = GetJsonSettings();
Console.WriteLine($"{content}");
return (T)JsonConvert.DeserializeObject<T>(content, settings);
}
Tried a bunch of things to fix it, but I'm honestly stumped. I'll also paste in the Deserialize method.
17 Replies
PapaMortality
PapaMortalityOP2y ago
Appricate any help. I'll try not to be too needy lol
Angius
Angius2y ago
What's the error, exactly?
PapaMortality
PapaMortalityOP2y ago
error CS0266: Cannot implicitly convert type 'object' to 'Cereal.Person' ing a cast?) Person np = Serializer.Deserialize<Person>("test.json"); On that line
Angius
Angius2y ago
(also, why Newtonsoft instead of the built-in Systen.Text.Json...?)
PapaMortality
PapaMortalityOP2y ago
uhh didnt know it existed Is it better?
Angius
Angius2y ago
Faster And built-in, so no need for any dependencies
PapaMortality
PapaMortalityOP2y ago
Does it serialize for me or do I have to set that up?
Angius
Angius2y ago
It works like Newtonsoft
PapaMortality
PapaMortalityOP2y ago
alrighty, ig ill do that one instead. Though i dont think this is a Newtonsoft issue
Angius
Angius2y ago
Yeah, it's most probably not
PapaMortality
PapaMortalityOP2y ago
I think im doin something wrong with my method or my generics idk
Angius
Angius2y ago
Your code should work, from what I can see That cast to T is unnecessary But shouldn't be causing any issues
PapaMortality
PapaMortalityOP2y ago
yeah, i did that to try and fix it lol oh bruh i restarted vscode and it disappeared
Angius
Angius2y ago
lmao
PapaMortality
PapaMortalityOP2y ago
alrighty well
Angius
Angius2y ago
VS Code moment
PapaMortality
PapaMortalityOP2y ago
thanks for the help loll ig ill also try system json

Did you find this page helpful?