gpt4 book ai didi

C# JavaScriptSerializer - 如何序列化为基本类型?

转载 作者:行者123 更新时间:2023-11-30 17:47:47 24 4
gpt4 key购买 nike

我在使用 JavaScriptSerializer 序列化时遇到问题。比如我有一个基类

public class MyBaseClass{
public int Id { get; set; }
public string Name { get; set; }
}

和派生类

public class MyDerivedClass : MyBaseClass {
public string Patronymic { get; set; }
}

如何将 MyDerivedClass 的实例序列化为 MyBaseClass?如果我不希望生成的 JSON 包含 Patronymic 属性?可能吗?

最佳答案

好吧,在扩展方法的帮助下,可以做一些非常通用的事情。将此类添加到您的项目中:

public static class Extensions
{
//Takes one object and return a new object with type T
public static T ToType<T>(this object value) where T : new()
{
var newValue = (T)Activator.CreateInstance(typeof(T));
SetProperties(value, newValue);
return newValue;
}

//Sets all properties with same name, from one source to target
private static void SetProperties(object source, object target)
{
var targetType = target.GetType();
var targetProperties = targetType.GetProperties();
foreach (var prop in source.GetType().GetProperties())
{
if (targetProperties.Any(p => p.Name == prop.Name))
{
var propGetter = prop.GetGetMethod();
var propSetter = targetType.GetProperty(prop.Name).GetSetMethod();
var valueToSet = propGetter.Invoke(source, null);
propSetter.Invoke(target, new[] { valueToSet });
}
}
}
}

然后您可以使用此代码将 MyDerivedClass 序列化为 MyBaseClass

var myDerivedObj = new MyDerivedClass { Id = 1, Name = "Test", Patronymic = "Patronymic" };
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var myDerivedString = serializer.Serialize(myDerivedObj);
var myBaseObj = myDerivedObj.ToType<MyBaseClass>(); //Converting
var myBaseString = serializer.Serialize(myBaseObj); //This string is what you want

关于C# JavaScriptSerializer - 如何序列化为基本类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24223879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com