/// <summary> /// Serializes object to Json string. /// </summary> /// <param name="source">Object to serialize.</param> /// <param name="omitTypeInfo">Whether to omit type information.</param> /// <returns>Json string.</returns> public static string SerializeJsonString(this object source, bool omitTypeInfo = false) { if (source == null) { throw new ArgumentNullException("source"); } string result = JsonSerializer.Serialize(source); if (omitTypeInfo) { return(JsonTypeInfoRegex.Replace(result, string.Empty)); } else { return(result); } }
/// <summary> /// Serializes object to Json string, write to file. /// </summary> /// <param name="source">Object to serialize.</param> /// <param name="filename">File name.</param> /// <param name="overwrite">Whether overwrite exists file.</param> /// <param name="omitTypeInfo">Whether to omit type information.</param> /// <returns>File full path.</returns> public static string WriteJson(this object source, string filename, bool overwrite = false, bool omitTypeInfo = false) { if (source == null) { throw new ArgumentNullException("source"); } if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } string fullPath = Path.GetFullPath(filename); string fullDirectoryPath = Path.GetDirectoryName(fullPath); if (!overwrite && File.Exists(filename)) { throw new ArgumentException("The specified file already exists.", fullPath); } if (!Directory.Exists(fullDirectoryPath)) { try { Directory.CreateDirectory(fullDirectoryPath); } catch { throw; } } string result = JsonSerializer.Serialize(source); if (omitTypeInfo) { result = JsonTypeInfoRegex.Replace(result, string.Empty); } File.WriteAllText(fullPath, result); return(fullPath); }