127 lines
3.1 KiB
C#
127 lines
3.1 KiB
C#
using System;
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
namespace xAiService.Helpers
|
|
{
|
|
public static class XAiMcpArgumentHelper
|
|
{
|
|
/// <summary>
|
|
/// Bind Parameters ...
|
|
/// </summary>
|
|
/// <param name="token"></param>
|
|
/// <param name="targetType"></param>
|
|
/// <returns></returns>
|
|
public static object Bind(
|
|
JToken token,
|
|
Type targetType
|
|
)
|
|
{
|
|
//
|
|
var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType;
|
|
|
|
//
|
|
// Null Handling ...
|
|
if (token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined)
|
|
{
|
|
//
|
|
if (!targetType.IsValueType || Nullable.GetUnderlyingType(targetType) != null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
//
|
|
return Activator.CreateInstance(targetType);
|
|
}
|
|
|
|
//
|
|
// Primitive Types ...
|
|
|
|
//
|
|
if (underlying == typeof(string))
|
|
{
|
|
return token.ToString();
|
|
}
|
|
|
|
//
|
|
if (underlying == typeof(int))
|
|
{
|
|
return token.Value<int>();
|
|
}
|
|
|
|
//
|
|
if (underlying == typeof(long))
|
|
{
|
|
return token.Value<long>();
|
|
}
|
|
|
|
//
|
|
if (underlying == typeof(short))
|
|
{
|
|
return token.Value<short>();
|
|
}
|
|
|
|
//
|
|
if (underlying == typeof(float))
|
|
{
|
|
return token.Value<float>();
|
|
}
|
|
|
|
//
|
|
if (underlying == typeof(double))
|
|
{
|
|
return token.Value<double>();
|
|
}
|
|
|
|
//
|
|
if (underlying == typeof(decimal))
|
|
{
|
|
return token.Value<decimal>();
|
|
}
|
|
|
|
//
|
|
if (underlying == typeof(bool))
|
|
{
|
|
return token.Value<bool>();
|
|
}
|
|
|
|
//
|
|
if (underlying == typeof(Guid))
|
|
{
|
|
return token.Value<Guid>();
|
|
}
|
|
|
|
//
|
|
if (underlying == typeof(DateTime))
|
|
{
|
|
return token.Value<DateTime>();
|
|
}
|
|
|
|
//
|
|
// Enum ...
|
|
if (underlying.IsEnum)
|
|
{
|
|
return Enum.Parse(underlying, token.ToString(), ignoreCase: true);
|
|
}
|
|
|
|
//
|
|
// Arrays ...
|
|
if (underlying.IsArray && token is JArray jarr)
|
|
{
|
|
//
|
|
var elementType = underlying.GetElementType();
|
|
var arr = Array.CreateInstance(elementType, jarr.Count);
|
|
for (var i = 0; i < jarr.Count; i++)
|
|
{
|
|
arr.SetValue(Bind(jarr[i], elementType), i);
|
|
}
|
|
|
|
//
|
|
return arr;
|
|
}
|
|
|
|
//
|
|
// Fallback: JSON Deserialize
|
|
return token.ToObject(underlying);
|
|
}
|
|
}
|
|
} |