标签:sof response ram ros clu utf8 efault byte sys
这里举例两种方式。
需要引用外部的 Newtonsoft.Json.dll
/// <summary>
/// 将json字符串转换为对象(使用Json.net)
/// </summary>
/// <param name="response"></param>
/// <param name="dateformatstring">时间格式</param>
/// <returns></returns>
public T JsonNetConvertJson<T>(string response)
{
try
{
//return JsonConvert.DeserializeObject<T>(response);
JsonSerializerSettings jsSetting = new JsonSerializerSettings();
jsSetting.NullValueHandling = NullValueHandling.Ignore;
return JsonConvert.DeserializeObject<T>(response, jsSetting);
}
catch (Exception ex)
{
WriteLog.WriteLogger.Error("将json字符串转换为对象出错!\r\njson为:" + response, ex);
return default(T);
}
}
Newtonsoft.Json.JsonSerializerSettings 是对返回数据的一些默认转换.
空值设置:
NullValueHandling 枚举默认是 Include,如果有 int 类型的字段是 null,会报错,把 JsonSerializerSettings.NullValueHandling 设置为 NullValueHandling.Ignore 之后,就会忽略值为 null 的字段。时间设置:
setting.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
/// <summary>
/// 将json字符串转换为对象(使用DataContractJsonSerializer)
/// </summary>
/// <param name="response"></param>
/// <param name="dateformatstring">时间格式</param>
/// <returns></returns>
public T ConvertJson<T>(string response)
{
try
{
DataContractJsonSerializer Serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(response)))
{
return (T)Serializer.ReadObject(stream);
}
}
catch (Exception ex)
{
WriteLog.WriteLogger.Error("将json字符串转换为对象出错!\r\njson为:" + response, ex);
return default(T);
}
}
标签:sof response ram ros clu utf8 efault byte sys
原文地址:https://www.cnblogs.com/MichaelLoveSna/p/14474512.html