using System; using System.Collections.Generic; using System.Text.Json; namespace Learn.Archives.Core.Common { public static class JsonExtractor { /// /// 提取json字符串 /// /// /// public static List ExtractJsonStrings(this string input) { List jsonList = new List(); int index = 0; while (index < input.Length) { if (input[index] == '{' || input[index] == '[') { int? endIndex = FindMatchingBracket(input, index); if (endIndex.HasValue) { string candidate = input.Substring(index, endIndex.Value - index + 1); if (IsValidJson(candidate)) { jsonList.Add(candidate); index = endIndex.Value + 1; continue; } } } index++; } return jsonList; } private static int? FindMatchingBracket(string str, int start) { Stack stack = new Stack(); bool inString = false; bool inEscape = false; for (int i = start; i < str.Length; i++) { char c = str[i]; if (inEscape) { inEscape = false; } else if (inString) { if (c == '\\') inEscape = true; else if (c == '"') inString = false; } else { switch (c) { case '{': case '[': stack.Push(c); break; case '}': if (stack.Count == 0 || stack.Peek() != '{') return null; stack.Pop(); break; case ']': if (stack.Count == 0 || stack.Peek() != '[') return null; stack.Pop(); break; case '"': inString = true; break; } } if (stack.Count == 0) return i; } return null; // 括号未完全匹配 } public static bool IsValidJson(string candidate) { if (string.IsNullOrEmpty(candidate)) return false; try { JsonDocument.Parse(candidate); return true; } catch (Exception) { return false; } } } }