我有这个类的实例:
public class MyClass
{
public string Username { get; set; }
public string Password { get; set; }
public string GetJson()
{
return JsonConvert.SerializeObject(this);
}
}
但在某些情况下,我需要序列化json中的更多属性。我以为我应该创建第二个这样的继承类:
public class MyInheritedClass : MyClass
{
public string Email { get; set; }
}
如果我没有以错误的方式解决问题,我怎么能用第一个类的实例初始化我的第二个类的新实例,并且有一个来自GetJson()
的json字符串,其中包含所有三个特性
答案 0 :(得分:5)
您可以在派生类中创建构造函数并映射对象
public class MyInheritedClass : MyClass
{
MyInheritedClass (MyClass baseObject)
{
this.UserName = baseObject.UserName; // Do it similarly for rest of the properties
}
public string Email { get; set; }
}
MyInheritedClass inheritedClassObject = new MyInheritedClass(myClassObject);
inheritedClassObject.GetJson();
更新了构造函数:
MyInheritedClass (MyClass baseObject)
{
//Get the list of properties available in base class
var properties = baseObject.GetProperties();
properties.ToList().ForEach(property =>
{
//Check whether that property is present in derived class
var isPresent = this.GetType().GetProperty(property);
if (isPresent != null)
{
//If present get the value and map it
var value = baseObject.GetType().GetProperty(property).GetValue(baseObject, null);
this.GetType().GetProperty(property).SetValue(this, value, null);
}
});
}
答案 1 :(得分:1)
您只需要创建一个MyInheritedClass
子类的实例,它将保存这两个类的所有属性。
当您创建子类MyInheritedClass
的实例时,运行时将首先调用Parent类MyInheritedClass
的构造函数来为父类的成员分配内存,然后调用子类构造函数。
因此,Child类的实例将具有所有属性,并且您在序列化对象时引用this
,因此它应该在json中序列化所有属性。
注意:即使您在父类中声明的方法内部序列化对象,引用this
对象也将引用作为Child类实例的当前实例,因此将保存所有属性。 / p>
答案 2 :(得分:1)
没有。您无法在基类对象中初始化派生实例。
但是你可以创建seprate扩展方法,
public class MyClass
{
public string Username { get; set; }
public string Password { get; set; }
public string GetJson()
{
return JsonConvert.SerializeObject(this);
}
}
public class MyInheritedClass : MyClass
{
public string Email { get; set; }
}
public static class MyClassExtension
{
public static MyInheritedClass ToMyInheritedClass(this MyClass obj, string email)
{
// You could use some mapper for identical properties. . .
return new MyInheritedClass()
{
Email = email,
Password = obj.Password,
Username = obj.Password
};
}
}
用法:
MyClass myClass = new MyClass { Username = "abc", Password = "123" };
var myInheritedClass = myClass.ToMyInheritedClass("abc@mail.com");
Console.WriteLine(myInheritedClass.GetJson());
输出将是:
{"Email":"abc@mail.com","Username":"123","Password":"123"}
答案 3 :(得分:1)
选项之一是序列化基类对象,然后将其反序列化为派生类。
例如。您可以使用Json.Net serializer
var jsonSerializerSettings = new JsonSerializerSettings
{ //You can specify other settings or no settings at all
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
string jsonFromBase = JsonConvert.SerializeObject(baseObject, Formatting.Indented, jsonSerializerSettings);
derivedClass= JsonConvert.DeserializeObject<DerivedClass>(jsonFromBase) ;