如下:
using Newtonsoft.Json;
using System.IO;
using System.Xml.Serialization;
public class JsonTool
{
static JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
public static string ToJson(object obj) { return JsonConvert.SerializeObject(obj, settings); }
public static T FromJson<T>(string json)
{
json ??= "";
return JsonConvert.DeserializeObject<T>(json, settings);
}
}
public class XmlTool
{
public static string ToXml<T>(T obj)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using var stringWriter = new StringWriter();
xmlSerializer.Serialize(stringWriter, obj);
return stringWriter.ToString();
}
public static T FromXml<T>(string xml)
{
XmlSerializer xmlSerializer = new(typeof(T));
return (T)xmlSerializer.Deserialize(new StringReader(xml));
}
}