I have following method, which is read JSON from the directory and de-serialize the JSON into C# class object.
public static JObject readJson(string fileName)
{
string JSON = "";
List<string> keyList = new List<string>();
using (StreamReader r = new StreamReader(fileName))
{
JSON = r.ReadToEnd();
}
JObject parsed = JObject.Parse(JSON);
var name = parsed["2"];
Numbers deserializedClass = JsonConvert.DeserializeObject<Numbers>(name.ToString());
return parsed;
}
Here you can see, I'm used class called Numbers
. I'm passing separate JSON file's name to the above method, based on that I also need to pass Class to convert JSON into C# object. How can I pass class to the above method as a generic? then I think I can modify this line,
var deserializedClass = JsonConvert.DeserializeObject<AnyClass>(name.ToString());
is it possible to do?
CodePudding user response:
try this:
public static JObject readJson<T>(string fileName)
{
string JSON = "";
List<string> keyList = new List<string>();
using (StreamReader r = new StreamReader(fileName))
{
JSON = r.ReadToEnd();
}
JObject parsed = JObject.Parse(JSON);
var name = parsed["2"];
Numbers deserializedClass = JsonConvert.DeserializeObject<T>(name.ToString());
return parsed;
}
https://docs.microsoft.com/en-us/dotnet/standard/generics/
https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/generics
CodePudding user response:
This method uses Generics and will take the Type you specify and return the object of that type.
public static T readJson<T>(string fileName)
{
var JSON = string.Empty;
using (var r = new StreamReader(fileName))
{
JSON = r.ReadToEnd();
}
var parsed = JObject.Parse(JSON);
var name = parsed["2"];
var deserializedClass = JsonConvert.DeserializeObject<T>(name.ToString());
return deserializedClass;
}
Usage:
var resultObject = readJson<Number>(fileName);