Вы можете вызвать 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"
}
}
}
Надеюсь, это поможет вам решить проблему.