NewtonSoft Json.NET 和单元素阵列

NewtonSoft Json.NET and Single Element Arrays

我有一些 JSon 正在使用 ToObject 方法转换为对象。

此 Json 的一部分有一个重复元素,在 Json 文本中正确表示为数组。当我正确转换它时,它被映射到 C# 对象

public IList<FooData> Foo { get; set; }

但是当我只有 1 个元素时,我收到一条错误消息,指出我试图解析为对象的 Json 不是数组,因为它周围没有 []

Json.NET是否支持单元素数组?

But when I only have 1 element I get an error saying that the Json that I am trying to Parse into an object is not an array because it does not have [] around it.

如果一个JSON文本周围没有[],那么它就不是一个单元素数组:实际上它是一个对象(例如:{ "text": "hello world" })。

尝试使用 JsonConvert.DeserializeObject 方法:

jsonText = jsonText.Trim();

// If your JSON string starts with [, it's an array...
if(jsonText.StartsWith("["))
{
    var array = JsonConvert.DeserializeObject<IEnumerable<string>>(jsonText);
}
else // Otherwise, it's an object...
{
    var someObject = JsonConvert.DeserializeObject<YourClass>(jsonText);
}

也可能发生 JSON 文本包含像 1"hello world" 这样的文字值...但我相信这些是非常极端的情况...

对于上述边缘情况,只需使用 JsonConvert.DeserializeObject<string>(jsonText) 反序列化它们(将 string 替换为 int 或其他...)。

确保你的 JSON 单项数组仍然指定为使用数组表示法的数组 []