Невозможно получить значения объекта в массиве Json - PullRequest
0 голосов
/ 23 апреля 2020

У меня проблема с чтением значений объекта в массив Json. пожалуйста, помогите мне в чем проблема здесь. Ниже мой код. Я отправляю список сотрудников, чтобы получить массив Json. но я не получаю 'EmployeeDetails' в массиве json (то есть на втором уровне).

в чем здесь проблема?

ниже мой код

class Program
    {
        static void Main(string[] args)
        {
            List<Employee> list = new List<Employee>();
            Employee emp = new Employee { ID = 101, Department = "Stocks", EmployeeDetails = new Name { FirstName = "S", LastName = "Charles", Email = "abc@gmail.com" } };
            Employee emp1 = new Employee { ID = 102, Department = "Stores", EmployeeDetails = new Name { FirstName = "L", LastName = "Dennis", Email = "Den@gmail.com" } };
            list.Add(emp);
            list.Add(emp1);
            var resul1t = Program.GetEmployeeDetails(list);
        }
        private static string GetEmployeeDetails(List<Employee> emp)
        {

            string jsonarray = "";
            if ((emp != null) && (emp.Count > 0))
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                int i = 0;
                foreach (var awo in emp)
                {
                    dic.Add(i.ToString(), ObjectToString(awo));
                    i++;
                }

                if (dic.Count > 0)
                {
                    jsonarray = DictionnaryToArray(dic);
                }
            }
            return jsonarray;
        }
        private static string ObjectToString(object obj)
        {
            Type objType = obj.GetType();
            IList<PropertyInfo> props = new List<PropertyInfo>(objType.GetProperties());
            StringBuilder sb = new StringBuilder(1024);
            foreach (PropertyInfo prop in props)
            {
                var type = prop.GetValue(obj, null);
                string attributeValueString = string.Format("\"{0}\":\"{1}\"", prop.Name, prop.GetValue(obj, null));

                if (type != null && type.GetType() == typeof(double))
                {
                    var doubleToStringValue = Convert.ToString(prop.GetValue(obj, null), System.Globalization.CultureInfo.InvariantCulture);
                    attributeValueString = string.Format("\"{0}\":\"{1:0.0}\"", prop.Name, doubleToStringValue);
                }
                sb.Append(attributeValueString).Append(";");
            }
            return "{" + sb.ToString().TrimEnd(new char[] { ';' }) + "}";
        }

        private static string DictionnaryToArray(Dictionary<string, object> data)
        {
            return "{" + string.Join(";", (from c in data select string.Format("\"{0}\":{1}", c.Key.ToString(), c.Value.ToString())).ToArray()) + "}";
        }
    }
    public class Employee
    {
        public int? ID { get; set; }
        public string Department { get; set; }
        public Name EmployeeDetails { get; set; }
    }
    public class Name
    {
        public string LastName { get; set; }
        public string Email { get; set; }
        public string FirstName { get; set; }
    }

Спасибо

1 Ответ

1 голос
/ 23 апреля 2020

Вы можете вызвать ObjectToString рекурсивно, когда у вас есть вложенный класс, я немного меняю ObjectToString, как показано в следующем коде:

private static string ObjectToString(object obj)
{
    Type objType = obj.GetType();
    IList<PropertyInfo> props = new List<PropertyInfo>(objType.GetProperties());
    StringBuilder sb = new StringBuilder(1024);

    foreach (PropertyInfo prop in props)
    {
        string attributeValueString;
        var type = prop.GetValue(obj, null);

        if (type != null && type.GetType() == typeof(double))
        {
            var doubleToStringValue = Convert.ToString(prop.GetValue(obj, null), System.Globalization.CultureInfo.InvariantCulture);
            attributeValueString = string.Format("\"{0}\":\"{1:0.0}\"", prop.Name, doubleToStringValue);
        }//new code
        else if (prop.PropertyType.IsNested)
        {
            attributeValueString = string.Format("\"{0}\":{1}", prop.Name, ObjectToString(type));
        }
        else
        {
            attributeValueString = string.Format("\"{0}\":\"{1}\"", prop.Name, type);
        }
        sb.Append(attributeValueString).Append(",");
    }//updated code ; by ,
    return "{" + sb.ToString().TrimEnd(new char[] { ',' }) + "}";
}

Обратите внимание, что вам нужно замените ; на ,, чтобы получить действительный json.

Результат

{
   "0":{
      "ID":"101",
      "Department":"Stocks",
      "EmployeeDetails":{
         "LastName":"Charles",
         "Email":"abc@gmail.com",
         "FirstName":"S"
      }
   },
   "1":{
      "ID":"102",
      "Department":"Stores",
      "EmployeeDetails":{
         "LastName":"Dennis",
         "Email":"Den@gmail.com",
         "FirstName":"L"
      }
   }
}

Надеюсь, это поможет вам решить проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...