一、序列化
通常我们返回json对象给客户端,需要新建一个类,因为有些数据对方是不需要,
就像一个类Person,里面有字段Name、Photo,而对方有要Photo也有不要Photo的,这个时候我们通过序列化 类指定
1.引入System.Web.Extensions
2.
var p = new Person { Name = "yc的客户", Photo = "hahaahh" };
var s = new PropertyVariableJsonSerializer();
string result1 = s.Serialize<Person>(p, new List<string>() { "Name" });
string result2 = s.Serialize<Person>(p, new List<string>() { "Name", "Photo" });
Console.WriteLine(result1);
Console.WriteLine(result2);
Console.ReadLine();
public class Person
{
public string Name { get; set; }
public string Photo { get; set; }
}
通用方法
public class PropertyVariableJsonSerializer
{
readonly System.Web.Script.Serialization.JavaScriptSerializer _serializer = new JavaScriptSerializer();
/**/
/// <summary>
/// json 序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="propertys"></param>
/// <returns></returns>
public string Serialize<T>(T obj, List<string> propertys)
{
_serializer.RegisterConverters(new[] { new PropertyVariableConveter(typeof(T), propertys) });
return _serializer.Serialize(obj);
}
}
public class PropertyVariableConveter : JavaScriptConverter
{
private readonly List<Type> _supportedTypes = new List<Type>();
public PropertyVariableConveter(Type supportedType, List<string> propertys)
{
_supportedTypes.Add(supportedType);
Propertys = propertys;
}
private List<string> Propertys { get; set; }
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new Exception(" 这个暂时不支持 , 谢谢 ");
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var dic = new Dictionary<string, object>();
var t = obj.GetType();
var properties = t.GetProperties();
foreach (var ite in properties)
{
string key = ite.Name;
var v = t.GetProperty(key).GetValue(obj, null);
if (Propertys == null || Propertys.Count <= 0)
{
dic.Add(key, v);
continue;
}
if (Propertys.Contains(key))
{
dic.Add(key, v);
}
}
return dic;
}
public override IEnumerable<Type> SupportedTypes
{
get { return _supportedTypes; }
}
}
二、反序列化
我们获取了一个json,但是我们不想写类,这个时候我能就可以使用
引入Newtonsoft.Json;
var p = new Person { Name = "yc的客户", Photo = "hahaahh" };
var s = new PropertyVariableJsonSerializer();
string result1 = s.Serialize<Person>(p, new List<string>() { "Name" });
string result2 = s.Serialize<Person>(p, new List<string>() { "Name", "Photo" });
var jo2 = JsonConvert.DeserializeObject<dynamic>(result2);
Console.WriteLine(jo2.Name);