I need deserialize a string with a special encode in a class, like the funcion "JsonConvert.DeserializeObject<>" of NewtonSoft library, I wrote this code:
public void getMembersInfo()
{
Dictionary<String, String> dict = new Dictionary<String, String>();
dict.Add("name", "Name Test");
dict.Add("address", "Addss Test");
Members test = DeserializeObject<Members>(dict);
Console.WriteLine("Var Name: " + test.name);
}
//Really "value" is a string type, but with "Dictionary" is more easy simulate the problem.
public static T DeserializeObject<T>(Dictionary<string, string> value)
{
var type = typeof(T);
var TheClass = (T)Activator.CreateInstance(type);
foreach (var item in value)
{
type.GetProperty(item.key).SetValue(TheClass, item.value, null);
}
return (T)TheClass;
}
public class Members
{
public String name;
public Int age;
public String address;
}
EDIT #1: The problem is that this code not work fine, do not what the problem with my question. It is difficult to explain in another language, so I wrote an example code, in it will should see the problem.
It would be extremely helpful if the code you posted in your question would actually compile. It really doesn't seem like you've taken the time to even try your code before you posted. With a little help from the compiler I worked out that you code should be like this:
The only thing that I think I can say that was an actual logic error was that you were using
.GetProperty(...)
when you should have been using.GetField(...)
.Otherwise it would suggest dropping the
(T)
on the linereturn (T)TheClass;
and also you should put awhere T : new
constraint on theDeserializeObject<T>
method and then simply callvar TheClass = new T();
.