弄清楚了。我必须实现一个自定义的 JsonConverter。正如其他人提到的,这不会产生有效/标准的 Json。
public class ObjectCollectionConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(object[]);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
object[] collection = (object[])value;
writer.WriteStartArray();
foreach (var item in collection)
{
if (item == null)
{
writer.WriteRawValue(""); // This procudes "nothing"
}
else
{
writer.WriteValue(item);
}
}
writer.WriteEndArray();
}
}
像这样使用它
Test t = new Test();
string json = JsonConvert.SerializeObject(t, new ObjectCollectionConverter());