using System; using System.Collections.Generic; using System.Text; using System.Text.Json; using System.Xml; namespace Common { /// /// 对json应用拓展 /// public static class YsJson { /// /// 将json字符串序列化为提供的匿名模版类型对象 /// /// /// /// 匿名模版类 /// /// public static T DeserializeAnonymousType(string json,T anonymousTypeObject, JsonSerializerOptions? options=null) { if (options == null) { options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };//忽略大小写 } return JsonSerializer.Deserialize(json,options); } /// /// json字符串反序列化为数据对象 自动忽略属性大小写 /// /// /// /// public static T JsonToObject(string json) { if (json.IsNull()) { return default(T); } try { return JsonSerializer.Deserialize(json, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); } catch { return default(T); } } /// ///自定义拓展获取对象数据 不存在则返回空值 /// /// /// /// public static string GetStrValue(this JsonElement Jsonobj,string propertyName) { string value = null; try { value = Jsonobj.GetProperty(propertyName).ToString(); } catch { value = null; } return value; } /// /// 对象数据转json /// /// /// public static string ToJson(object Data) { return Tools.ToJson(Data); } /// /// 将xml数据解析为Json /// /// public static string XmlToJson(string xmlStr) { try { var xmldoc = new XmlDocument(); xmldoc.LoadXml(xmlStr); string Jsonstr = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmldoc); return Jsonstr; } catch { return null; } } } }