如何将CSV列中的非标准JSON字符串转为C#的FoilJSON列表?
解决非标准JSON对象序列反序列化为List的问题
方法一:手动修正格式(最简单直接)
你的字符串本质是两个独立JSON对象用逗号分隔,仅缺少数组包裹。直接给字符串前后加方括号,再清理掉多余的首尾空白和末尾可能存在的逗号,就能用标准反序列化方法:
// 修正格式:包裹数组+清理冗余字符 string fixedFoils = $"[{foils.Trim().TrimEnd(',')}]"; // 标准反序列化 var converted = JsonSerializer.Deserialize<List<FoilJSON>>(fixedFoils);
方法二:用Newtonsoft.Json(Json.NET)直接解析
如果能引入Newtonsoft.Json NuGet包,它可以直接兼容这种非标准格式,无需手动修改字符串:
using Newtonsoft.Json; // 直接解析为List集合 var converted = JsonConvert.DeserializeObject<List<FoilJSON>>($"[{foils}]");
方法三:用System.Text.Json的Utf8JsonReader手动读取
不想引入第三方库的话,可借助Utf8JsonReader逐个解析每个JSON对象,完全不需要修改原始字符串:
using System.Text.Json; using System.Text; var foilList = new List<FoilJSON>(); byte[] jsonBytes = Encoding.UTF8.GetBytes(foils); using var reader = new Utf8JsonReader(jsonBytes, new JsonReaderOptions { AllowTrailingCommas = true }); // 遍历读取每个对象 while (reader.Read()) { if (reader.TokenType == JsonTokenType.StartObject) { var foil = JsonSerializer.Deserialize<FoilJSON>(ref reader); foilList.Add(foil); } }
方法四:正则分割解析(仅适合无嵌套对象的场景)
如果你的JSON对象内部没有嵌套的{}结构,可以用正则分割出每个独立对象,再逐个反序列化:
using System.Text.RegularExpressions; var matches = Regex.Matches(foils, @"\{[^{}]+\}", RegexOptions.Singleline); var foilList = new List<FoilJSON>(); foreach (Match match in matches) { var foil = JsonSerializer.Deserialize<FoilJSON>(match.Value); foilList.Add(foil); }
注意:若JSON存在嵌套对象,该方法会失效,优先选择前三种方案。
内容的提问来源于stack exchange,提问作者alrightgame
相关产品推荐
相关产品推荐

