" of NewtonSoft library, I wrote thi..." /> " of NewtonSoft library, I wrote thi..." /> " of NewtonSoft library, I wrote thi..."/>

Deserialize string in generic method c#

118 views Asked by At

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.

1

There are 1 answers

2
Enigmativity On BEST ANSWER

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:

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.GetField(item.Key).SetValue(TheClass, item.Value);
    }
    return (T)TheClass;
}

public class Members
{
    public String name;
    public int age;
    public String address;
}

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 line return (T)TheClass; and also you should put a where T : new constraint on the DeserializeObject<T> method and then simply call var TheClass = new T();.