1

The normal approach to serialisation is to apply attributes to your class to describe how serialisation (or deserialization) is to proceed. For example:

[DataContract]
class MyClass
{
   [DataMember]
   public string Name { get; set; }
}

Is there a way to perform serialisation using JSON.NET without applying attributes to your class, but instead by providing a "sidecar" object that describes what aspects of the class are to be serialised, in some fashion.

The reason I ask relates to separation of concerns. If you have an API that is meant to be agnostic about how requests get to it, then the natural extension of that is that your API data structures should not be getting embellished with serialisation attributes.

Now of course I could take the "content" of one of my API result objects and copy it into another object having a class that does have appropriate serialisation attributes, but in some cases it would seem more desirable to say "Hey, I want to serialise this object, and the object has no serialisation attributes, so here is a separate data structure to describe what to do."

The other place where this would be handy, of course, is with third-party libraries where you have no opportunity to modify the objects (again, you could make copies of the values, but I'm looking for other ways).

Kevmeister68
  • 216
  • 1
  • 2
  • 6
  • 1
    "sidercar" object is [DTO](http://stackoverflow.com/q/725348/1997232). If you can't/don't want to serialize data directly, then you can do it using DTO. Other thing is what you can control json serialization with it's own set of [attributes](http://www.newtonsoft.com/json/help/html/serializationattributes.htm). Set opt-in mode and mark only those fields/properties you want to serialize. They can be even be `private`. – Sinatr Apr 07 '16 at 07:40

1 Answers1

3

You can use JsonSerializerSettings to specify various serialization options. You can specify whether to serialize or not a particular property, how to serialize a particular type or convert its value, and etc.

     var settings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                .....
            };
     settings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
     settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
     settings.Binder = new SomeSerializationBinder(new DefaultSerializationBinder());

     var result = JsonConvert.SerializeObject(yourObject, settings);
Sergey L
  • 1,402
  • 1
  • 9
  • 11