lundi 8 mai 2023

How to get values from the array, that put into the object?

I am making json parser so I need the iniversal method, thats why I can not int[] arr = obj as int[];

 int[] array = new int[] { 0, 1, 2 };
 object obj = array;
//I need to get value from the 'obj'

I tried to use reflection, but my knowledge is not enough to solve the problem. Also I tried to use solutions from here How to extract elements of an array in object type in c#? but it did not help me.

UPD

I am getting random object, and I must convert it into json format ecma-404. But I got problems with converting arrays, because I can not get values.

   private static string ReadObject(object obj) {
            string json = "{";
            TypedReference reference = __makeref(obj);
            foreach(var fromField in obj.GetType().GetFields()) {
                var toField = obj.GetType().GetField(
                    fromField.Name, BindingFlags.Public | BindingFlags.Instance);

                object value = fromField.GetValueDirect(reference);
                if(value == null)  json += toField.Name + ':' + "null" + ',';
                else json += toField.Name + ':' + WriteValue(value, value.GetType()) + ',';

            }
            json = json.Remove(json.Length - 1);
            json += '}';
            return json;
        }


 public static string SerializeArray(object obj) {
            string json = "[";
//here must be code
            return json;
        }





Aucun commentaire:

Enregistrer un commentaire