object json
object json

Reputation: 615

The Difficulty of finding the object properties (reflection)

I wrote a program that does work with files like delete and update, store, and search And all customers But I have a problem with the method is Deserialize

I want the tab grid (Customer Grid ) when I click on any row in order to be seen for a specific customer.

But I think the main problem is in this line, this line is Deseriailize method.

var objProps = obj.GetType().GetProperties();

Because the code does not get the object properties properly

Project Files

Please see the video

 public T Deserialize<T>(string entity)
    {
        var obj = Activator.CreateInstance<T>();
        var stringProps = entity.Split(',');
        var objProps = obj.GetType().GetProperties();

        var propIndex = 0;

        for (int i = 0; i < stringProps.Length; i++)
        {
            try
            {
                if (objProps[propIndex].PropertyType.FullName == "System.String")
                {
                    objProps[propIndex].SetValue(obj, stringProps[i], null);
                }
                else if (objProps[propIndex].PropertyType.FullName == "System.Int32")
                {
                    objProps[propIndex].SetValue(obj, Convert.ToInt32(stringProps[i]), null);
                }
                else if (objProps[propIndex].PropertyType.FullName == "System.DateTime")
                {
                    var cultureInfo = new CultureInfo("fa-IR");
                    DateTime dateTime = Convert.ToDateTime(stringProps[i], cultureInfo);
                    objProps[propIndex].SetValue(obj, dateTime, null);
                }
                else
                {
                    i--;
                }
                propIndex++;
            }

            catch (IndexOutOfRangeException)
            {
                Debug.WriteLine("Index Out Of range");
            }
        }
        return obj;
    }

Upvotes: 0

Views: 98

Answers (1)

Konrad Kokosa
Konrad Kokosa

Reputation: 16898

Your problem is that you are calling Serializer.Deserialize<List<T>>(line) hence GetProperties() returns properties of List<T>, not T itself. They are:

  • Int32 Capacity
  • Int32 Count
  • OrderItem Int32

so what is your code trying to execute is to assign stringProps[i] with value 30/1/2008 to Int32 Count property.

Upvotes: 1

Related Questions