-2

I want to make a own parser that can parse object values into the <T> Type that contains class with propertys.

the class ASObject is just a Dictionary<string, object>

  public class Example {

    public string User { get; set; }
    public int Id { get; set; }

  }

  public static class ServiceResultParser<T>
  {
      public static T Parse(ASObject AS)
      {
          foreach(var l in AS.Values)
          {

          }
      }
  }

Usage:

var Result = ServiceResultParser.Parse<Example>(theobject);
string User = Result.User;

that is only a test class that I called Example in json we can use JsonConvert.DeserializeObject<T>(value)
and no I dont want parse json.
how can I now parse the value into the Example class?

regarding.

1 Answers1

0

You could check wheter T has a property with a name that matches the Dictionary's key:

  public static class ServiceResultParser<T> where T : new()
  {
      public static T Parse(ASObject AS)
      {
          var temp = GetObject();
          foreach(var l in AS)
          {
            PropertyInfo[] properties = typeof(T).GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if(property.Name == l.Key) property.SetValue(temp, l.Value);
                }
          }
          return temp;
      }
        protected T GetObject()
        {
            return new T();
        }
  }

You should also check if the properties type match, etc...

Alex Coronas
  • 468
  • 1
  • 6
  • 21