C#解析Json的类型转化的问题
2个回答
展开全部
Newtonsoft.Json.DLL,也可以用微软自带的JavaScriptSerializer
下面附JavaScriptSerializer代码:
/// <summary>
/// 将对象转换为JSON格式的字符串
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="target">对象目标</param>
/// <returns>转换结果</returns>
public static string JsonSerialize<T>(this T target)
{
T result = (T)target;
DataContractJsonSerializer json = new DataContractJsonSerializer(result.GetType());
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, result);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
/// <summary>
/// 将JSON格式字符转换成对象
/// </summary>
/// <typeparam name="T">需要转换的对象类型</typeparam>
/// <param name="target">JSON目标</param>
/// <returns>转换结果</returns>
public static T JsonDeserialize<T>(this string target)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(target)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
下面附JavaScriptSerializer代码:
/// <summary>
/// 将对象转换为JSON格式的字符串
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="target">对象目标</param>
/// <returns>转换结果</returns>
public static string JsonSerialize<T>(this T target)
{
T result = (T)target;
DataContractJsonSerializer json = new DataContractJsonSerializer(result.GetType());
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, result);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
/// <summary>
/// 将JSON格式字符转换成对象
/// </summary>
/// <typeparam name="T">需要转换的对象类型</typeparam>
/// <param name="target">JSON目标</param>
/// <returns>转换结果</returns>
public static T JsonDeserialize<T>(this string target)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(target)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询