Reputation: 701
Let's say I have 3 classes.
public Class1{
public string field1{get;set;}
}
public Class2:Class1 {
public string field2{get;set;}
}
public Class3:Class2 {
public string field3{get;set;}
}
Class3 obj3 = new Class3();
Class2 obj2 = obj3;
Class1 obj1 = obj2;
public class MyInfoService : ServiceBase<MyReuest>
{
protected override object Run(MyReuest request)
{
Class3 obj3= FindObjClass3("someid");
Class2 obj2 = DoSomethingObj3Class3(obj3);
Class1 obj1= obj2; // service users have to get only Class1 fields
return obj1;
}
}
The problem starts when I want to return obj1 as response with format=json , the output json contains properties from obj2 and obj3.
I just want that obj1 is serialized as response only with its properties.
Is there a way to do this ?
Upvotes: 2
Views: 1470
Reputation: 143319
Don't try and abuse inheritance, they're bad practice for DTOs: Getting ServiceStack to retain type information
It's also a bad idea to use inheritance to DRY properties - these unnecessary abstractions should be avoided. Automatic properties are a terse way to express the structural fields of your type. Use interfaces instead, when you need them: http://ayende.com/blog/4769/code-review-guidelines-avoid-inheritance-for-properties
Upvotes: 2
Reputation: 7747
If you can't touch serialization level, the try to Clone object before return.
public class Class1 : ICloneable {
public string Prop1 { get; set; }
public object Clone() {
return new Class1 { Prop1 = Prop1 };
}
}
public class Class2 : Class1 {
public string Prop2 { get; set; }
public new object Clone() {
return new Class2 { Prop1 = Prop1, Prop2 = Prop2 };
}
}
Then use use:
public class MyInfoService : ServiceBase<MyReuest>
{
protected override object Run(MyReuest request)
{
Class3 obj3 = FindObjClass3("someid");
Class2 obj2 = DoSomethingObj3Class3(obj3);
return ((Class1) obj2).Clone();
}
}
NOTE: For different implementations of Clone method depending on type use new
keyword instead of override
Upvotes: 1