3

I have a ASP.NET web API project and since it does not support having 2 body parameters, I use a JObject parameter and then extract the actual parameters from it. Like this.

Public bool mymethod(JObject data){
   myclassA a = data["a"].toObject<myclassA>();
   myclassA b = data["b"].toObject<myclassB>();
}

But the 2 class types implement ISerializable and I need the JSON.NET to ignore it. I have set up the default JSON.NET serializer to do that and it works fine when serialization is done automatically.

But I need to get a reference to the built in JSON.NET serializer so that I could use it like this in the above code.

myclassA b = data["b"].toObject<myclassB>(defaultSerializer);

Currently I create a new instance of the JSON.NET serializer and use it. But how can I get a reference to the default built in serializer in the asp.net WEB API ?

Also I cannot change anything in class types as this is sort of a legacy app that I'm converting to web api. Thanks.

1 Answer 1

11

Try this:

JsonSerializer serializer = JsonSerializer.Create(Configuration.Formatters.JsonFormatter.SerializerSettings);

That should give you the same serializer Web API uses.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, actually I'm using a slight variation of this. But this still calls JsonSerializer.Create() which creates a new instance of the serializer. I'm thinking if I could get reference to the serializer that has been already instantiated by the web api itself.
Web API creates a new serializer for each request. So that doesn't really mean anything. Json Serializers are very lightweight objects.
I had to use GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.
Thanks Dejan. Or here's the whole enchilada. System.Web.Http.GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
This kept from from having to [DataContract] and [DataMember] attribute many items. Instead of using "Newtonsoft.Json.JsonConvert.SerializeObject", using this kept the "backing field" style. My code in the next comment:
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.