Learn.Archives/Learn.Archives.Core/Common/JsonExtractor.cs

105 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Text.Json;
namespace Learn.Archives.Core.Common
{
public static class JsonExtractor
{
/// <summary>
/// 提取json字符串
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static List<string> ExtractJsonStrings(this string input)
{
List<string> jsonList = new List<string>();
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<char> stack = new Stack<char>();
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;
}
}
}
}