json序列化与反序列化
1,写到类中,用到DataContractJsonSerializer,需要引用using System.Runtime.Serialization;
public static class SerializerUtil { /// <summary>
/// json字符串反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonStr"></param>
/// <returns></returns>
public static T FromJson<T>(this string jsonStr)
{
try
{
DataContractJsonSerializer seri = new DataContractJsonSerializer(typeof(T));
using (MemoryStream memory = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
{
T jsonObj = (T)seri.ReadObject(memory);
return jsonObj;
}
}
catch
{
return default(T);//如果有异常会返回null
}
}
/// <summary>
/// json序列化
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static string ToJson(this object item)
{
try
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, item);
StringBuilder sb = new StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
return sb.ToString();
}
}
catch (Exception ex)
{
return "异常信息:"+ex.Message;
}
} }
使用例子:
//需要实例化的类要添加修饰符 [DataContractAttribute] class JsonMessage { [DataMemberAttribute] public string Id; [DataMemberAttribute] public string Msg; [DataMemberAttribute] public string Url; } static void Main(string[] args) { JsonMessage obj = new JsonMessage(); obj.Id = "1"; obj.Msg = "\u606d\u559c\u60a8,\u53d1\u5e03\u6210\u529f"; obj.Url = "http://post.88tc.com/149/105/s5"; //将对象直接变为json数据 string jsonStr = obj.ToJson(); //Console.WriteLine(jsonStr); JsonMessage obj2 = SerializerUtil.FromJson<JsonMessage>(jsonStr); Console.WriteLine(obj2.Msg); Console.Read(); }
输出结果是:恭喜您,发布成功。
obj.Msg的值是使用unicode编码表示的汉字。