using System.Collections; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// /// JsonExtensions /// public static class JsonExtensions { /// /// TryGetValue /// /// /// /// /// /// public static T GetValueOrDefault(this JObject jobj, string propertyName, T valueIfnotexist = default(T)) { if (jobj.TryGetValue(propertyName, out var value)) { return value.ToObject(); } return valueIfnotexist; } /// /// TryGetValue /// /// /// /// /// /// /// public static T GetValueOrDefault(this JObject jobj, string propertyName, JTokenType tokenType, T valueIfnotexist = default(T)) { if (jobj.TryGetValue(propertyName, out var value) && value.Type == tokenType) { return value.ToObject(); } return valueIfnotexist; } /// /// TryGetValue /// /// /// /// /// /// /// public static bool TryGetValue(this JObject jobj, string propertyName, JTokenType tokenType, out T outValue) { outValue = default(T); if (jobj.TryGetValue(propertyName, out var value) && value.Type == tokenType) { outValue = value.ToObject(); return true; } return false; } /// /// /// /// /// public static JToken ToJson(this object instance) => JToken.FromObject(instance); /// /// /// /// /// public static string ToJsonString(this object instance) => JToken.FromObject(instance).ToString(Formatting.None); /// /// parse json string then Deserialze to object /// /// /// /// public static T ParseJsonToObject(this string str) => JToken.Parse(str).ToObject(); /// /// /// /// /// public static JObject ToJObject(this object instance) => JObject.FromObject(instance); /// /// /// /// /// public static JArray ToJArray(this IEnumerable instances) => JArray.FromObject(instances); }