我很惊讶 - 但也许是因为我不知情 - JsonConvert.Deserialize<>()
会毫无怨言地解析这个格式错误的JSON:
{"Items": ["hello" "goodbye",]}
似乎使用了一些启发式方法来完成这项工作,在这种情况下,我认为做了正确的事情。&#34;但事实是,它默默地这样做是非常令人担忧的,因为我不知道我可以信任的行为。
旧版本的JSON.NET(6.x)会抛出错误,但较新版本(9.x)不会。此外,只使用Deserialize()的非泛型版本会抱怨语法错误 - 它只是不通用的。
我试图在dotnetfiddle上发布一个repro,但这并不起作用,因为即使你要求一个不同的版本,dotnetfiddle总是会加载JSON.NET的6.x版本。 (见https://dotnetfiddle.uservoice.com/forums/228764--net-fiddle-ideas/suggestions/10782315-load-the-specified-version-of-json-net-rather-than)。
所以,这是一个完整的repro(包括打印出正在使用的Netwonsoft.Json.Dll版本的代码)。它在9x版本的JSON.NET下打印2(因为它&#34;成功&#34;解析JSON)。在6.x之下,它会抛出一个错误(我认为应该这样)。
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
Console.WriteLine(typeof(JsonConvert).Assembly.GlobalAssemblyCache);
Console.WriteLine(typeof(JsonConvert).Assembly.FullName);
// I think this JSON is invalid because (1) it is missing a comma between the two values and (2) there is an extra comma at the end
string json = @"{""Items"": [""hello"" ""goodbye"",]}";
// This deserialize is successful and produces an object with two values for Items
Container result = JsonConvert.DeserializeObject<Container>(json);
Console.WriteLine(result.Items.Length + " items");
}
}
public class Container
{
public string[] Items { get; set; }
}
这种行为是否记录在案和/或是否常见?
在这种情况下有没有办法强制错误?
答案 0 :(得分:0)
我asked about this issue 在JSON.NET GitHub项目中。事实证明这是设计的。 James Newton-King的回应是:
JsonTextReader接受尾随逗号。 没有设置可以改变它,但你可以扮演角色 你自己更严格的JsonReader实现。