How to use Custom Serialization or Deserialization in WCF to force a new instance on every property of a datacontact ?

If your are using DataContract serialization then you can override its default behaviour using the OnDeserialized attribute. From MSDN: When applied to a method, specifies that the method is called during deserialization of an object in an object graph. The order of deserialization relative to other objects in the graph is non-deterministic. Here is my … Read more

Gson – deserialization to specific object type based on field value

You may implement a JsonDeserializer and use it while parsing your Json value to a Java instance. I’ll try to show it with a code which is going to give you the idea: 1) Define your custom JsonDeserializer class which creates different instance of classes by incoming json value’s id property: class MyTypeModelDeserializer implements JsonDeserializer<MyBaseTypeModel> … Read more

Json deserialization into other class hierarchy using Jackson

For this purpose you need to pass additional info in JSON: @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property=”@type”) class Base { … } Then on serialization it will add @type field: objectMapper.registerSubtypes( new NamedType(ConcreteAAdapter.class, “ConcreteA”), new NamedType(ConcreteBAdapter.class, “ConcreteB”), new NamedType(ConcreteCAdapter.class, “ConcreteC”) ); // note, that for lists you need to pass TypeReference explicitly objectMapper.writerWithType(new TypeReference<List<Base>>() {}) .writeValueAsString(someList); { “@type” … Read more

Json.NET: Deserializing nested dictionaries

I found a way to convert all nested objects to Dictionary<string,object> by providing a CustomCreationConverter implementation: class MyConverter : CustomCreationConverter<IDictionary<string, object>> { public override IDictionary<string, object> Create(Type objectType) { return new Dictionary<string, object>(); } public override bool CanConvert(Type objectType) { // in addition to handling IDictionary<string, object> // we want to handle the deserialization of … Read more

Deserialize array of key value pairs using Json.NET

The simplest way is deserialize array of key-value pairs to IDictionary<string, string>: public class SomeData { public string Id { get; set; } public IEnumerable<IDictionary<string, string>> Data { get; set; } } private static void Main(string[] args) { var json = “{ \”id\”: \”123\”, \”data\”: [ { \”key1\”: \”val1\” }, { \”key2\” : \”val2\” } … Read more