如何使用System.Text.Json解析含数字与字符串的嵌套JSON数组
使用System.Text.Json解析该嵌套JSON的可行方案
该JSON为二维嵌套数组结构,元素为混合类型(同时包含数值、字符串),无固定键名,值按固定位置存储。完全不需要通过String.Split()、String.Replace()手动处理:这类方式本质绕开JSON的标准语法规则,遇到字符串内的转义引号、特殊字符时,极易出现值错位、内容截断的问题,没有可靠性保障。
方案1:基于JsonDocument的只读解析(性能最优)
JsonDocument是System.Text.Json内置的只读解析组件,内存分配开销低,适合仅需读取数据、无需修改结构的场景。
核心实现代码:
using System.Text.Json; // 替换为实际从Web端获取的JSON响应字符串 string jsonResponse = """ [ [ 1499040000000, "0.01634790", "0.80000000", "0.01575800", "0.01577100", "148976.11427815", 1499644799999, "2434.19055334", 308, "1756.87402397", "28.46694368", "17928899.62484339" ] ] """; using JsonDocument parseResult = JsonDocument.Parse(jsonResponse); JsonElement rootElement = parseResult.RootElement; // 遍历外层数组的每条记录 foreach (JsonElement dataRow in rootElement.EnumerateArray()) { int elementCount = dataRow.GetArrayLength(); for (int index = 0; index < elementCount; index++) { JsonElement currentElement = dataRow[index]; // 根据JSON值类型做对应转换 switch (currentElement.ValueKind) { case JsonValueKind.Number: // 处理数值类型:如毫秒时间戳、整数成交笔数 long numericValue = currentElement.GetInt64(); break; case JsonValueKind.String: // 处理字符串类型:如带引号包裹的价格、交易量 string textValue = currentElement.GetString()!; // 高精度小数优先转decimal,避免浮点精度丢失 decimal decimalValue = decimal.Parse(textValue); break; } } }
注意:涉及金融交易类高精度数值时,不要直接对字符串包裹的数值调用
GetDecimal(),优先获取原始字符串文本后按指定格式解析,避免转换带来的精度偏差。
方案2:基于JsonNode的可编辑结构解析
如果后续需要修改解析后的数据、甚至需要把变更后的内容重新序列化为JSON,可使用JsonNode构建可操作的动态节点结构:
using System.Text.Json; using System.Text.Json.Nodes; string jsonResponse = """ [ [ 1499040000000, "0.01634790", "0.80000000", "0.01575800", "0.01577100", "148976.11427815", 1499644799999, "2434.19055334", 308, "1756.87402397", "28.46694368", "17928899.62484339" ] ] """; // 解析为可直接操作的动态节点 JsonArray rootArray = JsonNode.Parse(jsonResponse)!.AsArray(); // 按固定位置读取值 JsonArray singleRow = rootArray[0]!.AsArray(); long openTimestamp = (long)singleRow[0]!; string openPrice = (string)singleRow[1]!; long tradeRecordCount = (long)singleRow[8]!;
可选优化
由于该结构的数组元素位置是接口约定的固定顺序(对应固定业务字段),可以实现自定义JsonConverter,直接把数组反序列化为强类型业务对象,避免每次手动按索引取值。
内容的提问来源于stack exchange,提问作者user1257890
相关产品推荐
相关产品推荐

