使用递归和反射的JSON序列化.(阵列出现问题)



我目前正在尝试创建自己的JSON序列化方法,但当我调用"serialize"方法时,数组出现了问题,该方法的调用方式如下:

string person = MyJsonConverter.Serialize(new Clerk("Alexander", 1999, new List<string> { "Computer Science", "Web Developer" }));
Console.WriteLine(person);

它产生以下内容:

{"Skills": ["Capacity": "4", "Count": "2"], "Name": "Alexander", "YearOfBirth": "1999"}

但应该产生这个:

{"Skills": ["Computer Science", "Web Developer"], "Name": "Alexander", "YearOfBirth": "1999"}

我需要帮助的方法是,我不完全确定我做错了什么,但出于某种原因,它采用了数组的属性,而不是数组的值。

public static string Serialize(object obj)
{
StringBuilder stringBuilder = new StringBuilder();
IEnumerable<PropertyInfo> properties = obj.GetType().GetProperties().Where(p => p.GetIndexParameters().Length == 0);
if (typeof(IEnumerable).IsAssignableFrom(obj.GetType()))
stringBuilder.Append($"[");
else
stringBuilder.Append($"{{");
foreach (var property in properties)
if (property.PropertyType.IsPrimitive || property.PropertyType == typeof(string))
stringBuilder.Append($""{property.Name}": "{property.GetValue(obj)}", ");
else
stringBuilder.Append($""{property.Name}": {Serialize(property.GetValue(obj))}, ");
string temp = stringBuilder.ToString().Trim().Remove(stringBuilder.ToString().Length - 2);
stringBuilder.Clear();
stringBuilder.Append(temp);
if (typeof(IEnumerable).IsAssignableFrom(obj.GetType()))
stringBuilder.Append($"]");
else
stringBuilder.Append($"}}");
return stringBuilder.ToString();
}

我们非常感谢所有的帮助。

我这样做解决了这个问题:

public static string Serialize(object obj)
{
StringBuilder stringBuilder = new StringBuilder();
IEnumerable<PropertyInfo> properties = obj.GetType().GetProperties();
if (!obj.GetType().IsPrimitive && obj.GetType() != typeof(string))
{
bool isArray = typeof(IEnumerable).IsAssignableFrom(obj.GetType()) ? true : false;
if (isArray)
stringBuilder.Append($"[");
else
stringBuilder.Append($"{{");
if (!isArray)
foreach (var property in properties)
if (property.PropertyType.IsPrimitive || property.PropertyType == typeof(string))
stringBuilder.Append($""{property.Name}": "{property.GetValue(obj)}", ");
else
stringBuilder.Append($""{property.Name}": {Serialize(property.GetValue(obj))}, ");
else
foreach (var i in obj as IEnumerable)
if (i.GetType().IsPrimitive || i.GetType() == typeof(string))
stringBuilder.Append($""{i}", ");
else
stringBuilder.Append($"{Serialize(i)}, ");
stringBuilder.Remove(stringBuilder.ToString().Length - 2, 2);
if (isArray)
stringBuilder.Append($"]");
else
stringBuilder.Append($"}}");
}
else
stringBuilder.Append(obj.ToString());
return stringBuilder.ToString();
}

它可能不是最漂亮的,但它很管用。

我仍然愿意接受建议。

最新更新