98 lines
2.2 KiB
C#
98 lines
2.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text.Json;
|
|
using static System.Runtime.InteropServices.JavaScript.JSType;
|
|
|
|
namespace VideoAnalysisCore.Common
|
|
{
|
|
public static class JsonExtractor
|
|
{
|
|
/// <summary>
|
|
/// 提取json字符串
|
|
/// </summary>
|
|
/// <param name="input"></param>
|
|
/// <returns></returns>
|
|
public static List<string> ExtractJsonStrings(this string input)
|
|
{
|
|
var results = new List<string>();
|
|
if (string.IsNullOrWhiteSpace(input)) return results;
|
|
|
|
int braceCount = 0;
|
|
int bracketCount = 0;
|
|
int startIndex = -1;
|
|
bool inString = false;
|
|
bool isEscaped = false;
|
|
|
|
for (int i = 0; i<input.Length; i++)
|
|
{
|
|
char c = input[i];
|
|
|
|
// 1. 处理转义字符 (例如 \")
|
|
if (isEscaped)
|
|
{
|
|
isEscaped = false;
|
|
continue;
|
|
}
|
|
|
|
if (c == '\\')
|
|
{
|
|
isEscaped = true;
|
|
continue;
|
|
}
|
|
|
|
// 2. 处理字符串边界
|
|
if (c == '"')
|
|
{
|
|
inString = !inString;
|
|
continue;
|
|
}
|
|
|
|
// 3. 如果在字符串内,忽略括号逻辑
|
|
if (inString) continue;
|
|
|
|
// 4. 处理 JSON 对象和数组的开始
|
|
if (c == '{' || c == '[')
|
|
{
|
|
if (braceCount == 0 && bracketCount == 0)
|
|
{
|
|
startIndex = i;
|
|
}
|
|
if (c == '{') braceCount++;
|
|
else bracketCount++;
|
|
}
|
|
// 5. 处理 JSON 对象和数组的结束
|
|
else if (c == '}' || c == ']')
|
|
{
|
|
if (c == '}') braceCount--;
|
|
else bracketCount--;
|
|
|
|
if (braceCount == 0 && bracketCount == 0 && startIndex != -1)
|
|
{
|
|
string potentialJson = input.Substring(startIndex, i - startIndex + 1);
|
|
if (IsValidJson(potentialJson))
|
|
{
|
|
results.Add(potentialJson);
|
|
}
|
|
startIndex = -1;
|
|
}
|
|
}
|
|
}
|
|
return results;
|
|
}
|
|
|
|
public static bool IsValidJson(string candidate)
|
|
{
|
|
if (string.IsNullOrEmpty(candidate))
|
|
return false;
|
|
try
|
|
{
|
|
JsonDocument.Parse(candidate);
|
|
return true;
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
} |