Advertisement
Pro_Unit

JsonExtensions

Jun 24th, 2022
1,386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | None | 0 0
  1. namespace StrongExtensions
  2. {
  3.     public static class JsonExtensions
  4.     {
  5.         private static readonly JsonSerializerSettings Settings = new()
  6.         {
  7.             Converters =
  8.             {
  9.                 new ColorConverter(),
  10.                 new UnityObjectConverter(),
  11.                 new IntReactivePropertyJsonConverter(),
  12.                 new FloatReactivePropertyJsonConverter(),
  13.                 new StringReactivePropertyJsonConverter(),
  14.             }
  15.         };
  16.  
  17.         public static string ToJson<T>(this T target, bool prettyPrint = false)
  18.         {
  19.             Formatting formatting = prettyPrint
  20.                 ? Formatting.Indented
  21.                 : Formatting.None;
  22.  
  23.             return JsonConvert.SerializeObject(target, formatting, Settings);
  24.         }
  25.  
  26.         public static T FromJson<T>(this string json) =>
  27.             JsonConvert.DeserializeObject<T>(json, Settings);
  28.  
  29.         public static string ToPrettyJson<T>(this T target, string name = "") =>
  30.             $"{name} : \n{JsonConvert.SerializeObject(target, Formatting.Indented, Settings)}";
  31.  
  32.         public static T LogAsJson<T>(this T value, string name = "")
  33.         {
  34.             Type type = typeof(T);
  35.             if (name.IsNullOrEmpty())
  36.                 name = type.Name;
  37.  
  38.             string prettyJson = value.ToPrettyJson(name);
  39.             Debug.Log(prettyJson);
  40.             return value;
  41.         }
  42.         public static IEnumerable<T> LogAsJson<T>(this IEnumerable<T> source, string name = null)
  43.         {
  44.             IEnumerable<T> log = source as T[] ?? source.ToArray();
  45.  
  46.             Debug.Log(log.Count());
  47.  
  48.             if (name.IsNullOrEmpty())
  49.                 name = typeof(T).Name;
  50.  
  51.             Debug.Log(log.ToPrettyJson(name));
  52.  
  53.             return log;
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement