在某些情况下,序列化将输出无效的JSON字符串。
该行为似乎与“处理”错误有关,但JSON.NET使输出处于无效状态。
附上一个小程序来重现:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace JsonNetBug
{
class Program
{
static void Main()
{
var settings = new JsonSerializerSettings();
settings.Error += (obj, args) =>
{
args.ErrorContext.Handled = true;
};
var data = new List<Person>()
{
new Person{FirstName = "Scott", LastName = "Hanselman"},
new Person{FirstName = "Scott", LastName = "Hunter"},
new Person{FirstName = "Scott", LastName = "Guthrie"},
};
var dictionary = data.GroupBy(person => person.FirstName).ToDictionary(group => @group.Key, group => @group.Cast<IPerson>());
var output = JsonConvert.SerializeObject(dictionary, Formatting.None, settings);
Console.WriteLine(output);
Console.ReadLine();
}
}
interface IPerson
{
}
class Person//:IPerson - oops! Forgot to implement the person interface
{
public string LastName { get; set; }
public string FirstName { get; set; }
}
}
更新:
忘了提及它写出{"Scott":}
时出现的格式错误。应该写出来的是{"Scott":null}