using System.Globalization;
using System.Text;
using System.Text.Json.Nodes;
namespace XFEWorkflow.Core.Runtime;
public static class WorkflowObjectFields
{
public static (JsonNode? Value, bool Found) Read(JsonNode? source, string path)
{
if (source is not JsonObject and not JsonArray)
throw new ArgumentException("读取对象字段需要对象或数组;JSON 文本请先使用类型转换节点解析");
if (path.Length == 0) return (source.DeepClone(), true);
var parts = path.StartsWith('/') ? path[1..].Split('/').Select(PointerSegment) : path.Split('.');
JsonNode? current = source;
foreach (var part in parts)
{
if (current is JsonObject obj && obj.TryGetPropertyValue(part, out var field)) current = field;
else if (current is JsonArray array && int.TryParse(part, NumberStyles.None, CultureInfo.InvariantCulture, out var index) && index < array.Count) current = array[index];
else return (null, false);
}
return (current?.DeepClone(), true);
}
private static string PointerSegment(string segment)
{
var result = new StringBuilder(segment.Length);
for (var i = 0; i < segment.Length; i++)
{
if (segment[i] != '~') { result.Append(segment[i]); continue; }
if (++i >= segment.Length || segment[i] is not '0' and not '1')
throw new ArgumentException("JSON Pointer 字段路径中的 ~ 只能写成 ~0(~)或 ~1(/)");
result.Append(segment[i] == '0' ? '~' : '/');
}
return result.ToString();
}
}
using System.Globalization;
using System.Text;
using System.Text.Json.Nodes;
namespace XFEWorkflow.Core.Runtime;
public static class WorkflowObjectFields
{
public static (JsonNode? Value, bool Found) Read(JsonNode? source, string path)
{
if (source is not JsonObject and not JsonArray)
throw new ArgumentException("读取对象字段需要对象或数组;JSON 文本请先使用类型转换节点解析");
if (path.Length == 0) return (source.DeepClone(), true);
var parts = path.StartsWith('/') ? path[1..].Split('/').Select(PointerSegment) : path.Split('.');
JsonNode? current = source;
foreach (var part in parts)
{
if (current is JsonObject obj && obj.TryGetPropertyValue(part, out var field)) current = field;
else if (current is JsonArray array && int.TryParse(part, NumberStyles.None, CultureInfo.InvariantCulture, out var index) && index < array.Count) current = array[index];
else return (null, false);
}
return (current?.DeepClone(), true);
}
private static string PointerSegment(string segment)
{
var result = new StringBuilder(segment.Length);
for (var i = 0; i < segment.Length; i++)
{
if (segment[i] != '~') { result.Append(segment[i]); continue; }
if (++i >= segment.Length || segment[i] is not '0' and not '1')
throw new ArgumentException("JSON Pointer 字段路径中的 ~ 只能写成 ~0(~)或 ~1(/)");
result.Append(segment[i] == '0' ? '~' : '/');
}
return result.ToString();
}
}