using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; using UnityEngine; namespace NBF { public static class JTokenExtends { public static Vector2 ToVector2(this string str, string sp = ",") { Vector2 vector2 = Vector2.zero; var arr = str.Split(sp); if (arr.Length > 0) { float.TryParse(arr[0], out vector2.x); if (arr.Length > 1) { float.TryParse(arr[1], out vector2.y); } } return vector2; } public static Vector3 ToVector3(this string str, string sp = ",") { Vector3 vector2 = Vector3.zero; var arr = str.Split(sp); if (arr.Length > 0) { float.TryParse(arr[0], out vector2.x); if (arr.Length > 1) { float.TryParse(arr[1], out vector2.y); } if (arr.Length > 2) { float.TryParse(arr[2], out vector2.z); } } return vector2; } public static T[] ToArr(this JToken token, string split = ",") where T : IConvertible { if (token is JArray array) { return array.ToObject(); } if (token != null) { var str = token.ToString(); if (string.IsNullOrWhiteSpace(str)) return Array.Empty(); var arr = str.Split(split); try { return arr.Select(a => (T)Convert.ChangeType(a, typeof(T))).ToArray(); } catch (Exception e) { Console.WriteLine(e); throw; } } return Array.Empty(); } public static int ToInt(this JToken token) { if (token == null) { return 0; } try { return (int)token; } catch (Exception e) { return 0; } } public static float ToFloat(this JToken token) { if (token == null) { return 0; } try { return (float)token; } catch (Exception e) { return 0; } } public static string ToStr(this JToken token) { if (token != null) { return token.ToString(); } return string.Empty; } public static List ToList(this JToken token, string split = ",") where T : IConvertible { if (token is JArray array) { return array.ToObject>(); } if (token != null) { var str = token.ToString(); if (string.IsNullOrWhiteSpace(str)) return new List(); var arr = str.Split(split); return arr.Select( a => string.IsNullOrWhiteSpace(a) ? default : (T)Convert.ChangeType(a, typeof(T))).ToList(); } return new List(); } } }