You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.9 KiB
C#

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