/// <summary> /// Dynamically creates an instance of JSON.NET /// </summary> /// <param name="throwExceptions">If true throws exceptions otherwise returns null</param> /// <returns>Dynamic JsonSerializer instance</returns> public static dynamic CreateJsonNet(bool throwExceptions = true) { if (JsonNet != null) { return(JsonNet); } lock (SyncLock) { if (JsonNet != null) { return(JsonNet); } // Try to create instance dynamic json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); if (json == null) { try { json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); } catch { if (throwExceptions) { throw; } return(null); } } if (json == null) { return(null); } if (FormattingType == null) { FormattingType = ReflectionUtils.GetTypeFromName("Newtonsoft.Json.Formatting"); } JsonTextReaderType = ReflectionUtils.GetTypeFromName("Newtonsoft.Json.JsonTextReader"); JsonTextWriterType = ReflectionUtils.GetTypeFromName("Newtonsoft.Json.JsonTextWriter"); json.ReferenceLoopHandling = (dynamic)ReflectionUtils.GetStaticProperty("Newtonsoft.Json.ReferenceLoopHandling", "Ignore"); // Enums as strings in JSON dynamic enumConverter = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.Converters.StringEnumConverter"); json.Converters.Add(enumConverter); JsonNet = json; } return(JsonNet); }
/// <summary> /// Takes a single line JSON string and pretty formats /// it using indented formatting. /// </summary> /// <param name="json"></param> /// <returns></returns> public static string FormatJsonString(string json) { Type type = ReflectionUtils.GetTypeFromName("Newtonsoft.Json.Linq.JToken"); var formatting = (dynamic)Enum.Parse(FormattingType, "Indented"); dynamic jvalue = type.InvokeMember("Parse", BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, type, new object[] { json }); return(jvalue.ToString(formatting) as string); }
static JsonSerializationUtils() { // Ensure JSON.NET is loaded FormattingType = ReflectionUtils.GetTypeFromName("Newtonsoft.Json.Formatting"); // if not loaded yet try to load assembly if (FormattingType == null) { AppDomain.CurrentDomain.Load("Newtonsoft.Json"); FormattingType = ReflectionUtils.GetTypeFromName("Newtonsoft.Json.Formatting"); if (FormattingType == null) { throw new InvalidOperationException( Resources.JSON_NET_library_not_avaiable); } } }