Json與Object互轉工具類
public static class Serialization
{
public static T JsonToObject<T>(string jsonText)
{
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
T result = (T)((object)dataContractJsonSerializer.ReadObject(memoryStream));
memoryStream.Dispose();
return result;
}
public static string ObjectToJSON<T>(T obj)
{
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
string result = string.Empty;
using (MemoryStream memoryStream = new MemoryStream())
{
dataContractJsonSerializer.WriteObject(memoryStream, obj);
memoryStream.Position = 0L;
using (StreamReader streamReader = new StreamReader(memoryStream))
{
result = streamReader.ReadToEnd();
}
}
return result;
}
}
本文來自部落格園,作者:農碼一生,轉載請注明原文連結:https://www.cnblogs.com/wml-it/p/15513583.html
技術的發展日新月異,随着時間推移,無法保證本部落格所有内容的正确性。如有誤導,請大家見諒,歡迎評論區指正! 個人開源代碼連結: GitHub:https://github.com/ITMingliang
Gitee:https://gitee.com/mingliang_it
GitLab:https://gitlab.com/ITMingliang
進開發學習交流群: