0

I am facing problem with reading object values into Json array. please help me what is the problem here. Below is my code. I am sending employee list to get Json array. but i am not getting 'EmployeeDetails' in json array(that is in second level).

what is the problem here?

below is my code

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 = "[email protected]" } };
            Employee emp1 = new Employee { ID = 102, Department = "Stores", EmployeeDetails = new Name { FirstName = "L", LastName = "Dennis", Email = "[email protected]" } };
            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; }
    }

Thanks

1 Answer 1

1

You could call ObjectToString recursively when you have a nested class, i'm changing little the ObjectToString, like the following code:

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[] { ',' }) + "}";
}

Note that, you need to replace ; by , to get a valid json.

Result

{
   "0":{
      "ID":"101",
      "Department":"Stocks",
      "EmployeeDetails":{
         "LastName":"Charles",
         "Email":"[email protected]",
         "FirstName":"S"
      }
   },
   "1":{
      "ID":"102",
      "Department":"Stores",
      "EmployeeDetails":{
         "LastName":"Dennis",
         "Email":"[email protected]",
         "FirstName":"L"
      }
   }
}

I hope this helps you fix the issue.

Sign up to request clarification or add additional context in comments.

7 Comments

hi Sajid, i am still not getting the expected result.
@new_learner you don't get EmployeeDetails in your json result? if you don't copy/paste my update, you don't forget to replace ; by , in DictionnaryToArray and delete \" in this line attributeValueString = string.Format("\"{0}\":{1}", prop.Name, ObjectToString(type));
yes. i modified the Method as u suggested. but not getting EmployeeDetails in json array
i updated my comment, can you show me what have you added in else if (prop.PropertyType.IsNested) it gives me the result add in the answer.
i think you miss to call ObjectToString in attributeValueString = string.Format("\"{0}\":{1}", prop.Name, ObjectToString(type))
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.