Newtonsoft Json Serialize Derived Class Only

  1. Newtonsoft Json Serialize Derived Class Only Available
  2. Newtonsoft Json Serialize Derived Class Only For One
Active3 years ago

This sample creates a class that inherits from T:Newtonsoft.Json.Converters.CustomCreationConverter`1 that instantiates Employee instances for the Person type. How to: Control Serialization of Derived Classes.; 4 minutes to read +1; In this article. Using the XmlElementAttribute attribute to change the name of an XML element is not the only way to customize object serialization. I was just working with Json.NET in C# and was looking for a solution to create a JSON-String from an object where I only wanted to put in the properties of the base type, as I have stored subtypes in memory which contain additional ViewModel properties that were unneeded as I only needed the business data. This sample deserializes JSON to an object. Serialize Raw JSON value. Deserialize JSON from a file. Populate an Object. One more thought. If you can work around the limitation of outputting the extra XML elements, you are able to serialize the derived class using only the base object by either 1) using XmlIncludeAttributes on the base class to tell it which types to expect or 2) using the XmlSerializer constructor overload that takes a list of types.

.

Hello,

JSON deserialization with JSON.net: class hierarchies In part 1 of this series I described the basics of creating classes from a JSON string and then simply deserializing the string into a (list of) classes.

I have this sample code :

If I create this instance :

Newtonsoft json serialize derived class only for sale

When I serialize this object like that :

I obtain this :

But, in my project, I don't have to have informations on derived classes, I would like only elements of base classes from this instance like this :

The Xml :

Can you please, help me to obtain the good Xml (only with base type Vehicule and Brand) ?

Many thanks

BobBob
3361 gold badge7 silver badges20 bronze badges

2 Answers

You can't magically serialize a derived class as it's base because

Autocad for beginners pdf. '..Serialization checks type of instance by calling Object.getType() method. This method always returns the exact type of object.'

The solution here, if you really need to only serialize the base class is to implement the IXmlSerializable interface and create your own custom serializer.

IXmlSerializable:http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable(v=vs.110).aspx

One more thought. If you can work around the limitation of outputting the extra XML elements, you are able to serialize the derived class using only the base object by either 1) using XmlIncludeAttributes on the base class to tell it which types to expect or 2) using the XmlSerializer constructor overload that takes a list of types.

Edit:After thinking about this a little more, a workaround would be that you would add a Clone() method onto your base object, then serialize the clone of the base.

LinqPad code:

Wyatt EarpWyatt Earp

This is one of the issues with inheritance, and another reason to favor composition imho.

I ran into the same issue on a mobile app where I had a Contact class that derives from ContactSummary. The repository returns Contact instances, but in lots of cases I only wanted the ContactSummary going over the wire to save on message sizes and data usage etc. The default Xml and Json serialisers would only work when the derived class was attributed with the [KnownType()] of the base class, but this still meant all those extra properties going over the wire.

Using inheritance it is problematic to achieve a viable solution, and I didn't want to resort to custom serialisers, and if the solution is to pollute the DTO with copy constructors and clone properties, then why not change the DTO to use composition instead?

Json

If you have control over your DTOs, then restructuring them to use composition rather than inheritance may be the answer. In my example it was fairly simple..

In your example, Car would need to contain a reference to Vehicle not inherit from it - something like..

Then when you want the 'base' type in your example, simply serialise Car.Vehicle.

controlboxcontrolbox

Not the answer you're looking for? Browse other questions tagged c#serialization or ask your own question.

Active1 year, 10 months ago

Given a data model:

Electronic user manuals. Manuals and free owners instruction pdf guides. Find the user manual and the help you need for the products you own at ManualsOnline. View & download of more than 261 Tc electronic PDF user manuals, service manuals, operating guides. Music pedal user manuals, operating guides & specifications.

For implementation convenience reasons, there are times when the ChildId objects on the Parent are in fact ChildDetail objects. When I use JSON.net to serialize the Parent, they are written out with all of the ChildDetail properties.

Is there any way to instruct JSON.net (or any other JSON serializer, I'm not far enough into the project to be committed to one) to ignore derived class properties when serializing as a base class?

EDIT: It is important that when I serialize the derived class directly that I'm able to produce all the properties. I only want to inhibit the polymorphism in the Parent object.

Newtonsoft Json Serialize Derived Class Only Available

Christopher Currie
Christopher CurrieChristopher Currie
2,2971 gold badge22 silver badges39 bronze badges

6 Answers

I use a custom Contract Resolver to limit which of my properties to serialize. This might point you in the right direction.

e.g.

In the override IList function, you could use reflection to populate the list with only the parent properties perhaps.

Contract resolver is applied to your json.net serializer. This example is from an asp.net mvc app.

Nick Craver
552k117 gold badges1221 silver badges1118 bronze badges
Jason WattsJason Watts

I had the exact same problem and looked up how to build the ContractResolver I was actually looking for and that better answer this question. This only serializes the Properties of the Type T you actually want to serialize, but with this example you can also easily build similar approaches:

AkkuAkku
3,2784 gold badges38 silver badges64 bronze badges

Having encountered a similar problem, this is the ContractResolver I came up with:

It cuts off only the properties of targetType's descendants, without affecting the properties of its base classes or of other types that targetType's properties might reference. Which, depending on your needs, may or may not be an improvement over the other answers provided here at the time.

HellBrick

Newtonsoft Json Serialize Derived Class Only For One

HellBrick
3531 gold badge4 silver badges10 bronze badges

Check out the answers in this similar thread, particularly the IgnorableSerializerContractResolver in my answer and the nicer lambda version

Usage:

Community
drzausdrzaus
16.6k7 gold badges93 silver badges155 bronze badges

I have not used JSON.Net in particular so not positive this will help you. If JSON.Net derives itself from the .Net serialization system then you should be able to add the [NonSerialized] attribute to your properties you do now wish to be serialized in the base class. When you call the serialize methods on the base class, serialization should then skip those elements.

BuellerBueller

Haven't compared performance implications, but this is a working solution as well, and works with nested/referenced objects as well.

martinossmartinoss
3,1112 gold badges34 silver badges40 bronze badges

Not the answer you're looking for? Browse other questions tagged c#serializationjson.net or ask your own question.

Comments are closed.