C#如何兼容反序列化单对象和多对象拼接的两种JSON格式?
场景说明
存在两种输入JSON格式如下:
- 格式1:单个合法JSON对象,结构为
{"T":"q",...},可直接反序列化为Quote类型 - 格式2:多个JSON对象直接用逗号拼接,无外层数组方括号,结构为
{"T":"q",...}, {"T":"q",...},直接反序列化为List<Quote>会报错
原始错误信息:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[JasonTest.Quote]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'T', line 1, position 5.
错误原因
格式2不属于标准JSON数组结构,缺少外层[]包裹,和List<T>的反序列化要求不匹配。
解决方案
方案1:字符串预处理(简单高效,适合绝大多数场景)
给输入字符串首尾强制加[]转成标准JSON数组,统一反序列化为List<Quote>,格式1输入会返回长度为1的列表,自动兼容两种场景:
using Newtonsoft.Json; using System.Collections.Generic; public List<Quote> DeserializeQuotes(string jsonInput) { string standardArrayJson = $"[{jsonInput.Trim()}]"; return JsonConvert.DeserializeObject<List<Quote>>(standardArrayJson); }
该方案不会影响JSON内部的嵌套对象、字符串中的逗号,仅修改最外层结构,稳定性足够覆盖大部分业务场景。
方案2:流式读取(更严谨,适合特殊边界场景)
如果输入存在首尾多余空白、杂项字符等特殊情况,可以用JsonTextReader的多内容支持特性,直接逐个读取顶层JSON对象,不需要修改原字符串:
using Newtonsoft.Json; using System.Collections.Generic; using System.IO; public List<Quote> DeserializeQuotes(string jsonInput) { List<Quote> result = new List<Quote>(); using (StringReader sr = new StringReader(jsonInput)) using (JsonTextReader reader = new JsonTextReader(sr)) { // 开启多顶层内容支持 reader.SupportMultipleContent = true; JsonSerializer serializer = new JsonSerializer(); while (reader.Read()) { if (reader.TokenType == JsonToken.StartObject) { Quote item = serializer.Deserialize<Quote>(reader); result.Add(item); } } } return result; }
两种方案最终返回统一的List<Quote>类型,调用侧无需判断输入格式,直接按列表处理即可。
内容的提问来源于stack exchange,提问作者G Chu

