1

I know there are options to serialize Type info in Json.Net.

We can add type info to json object as $type property.

But both TypeNameHandling.Objects and TypeNameHandling.Array options increase message size dramatically.

I need to serialize root element type info. I have complex object and I need only main object type info.

How can I achieve it? Could I write new TypeNameHandling or how?

SAMPLE C# OBJECTS AND DESIRED JSON RESULT

public class MainComplexObject
{
    public int Id { get; set; }
    public IEnumerable<B> BList { get; set; }
}

public class B
{
    public int Id { get; set; }
    public string Name { get; set; }

    public C C { get; set; }
}

public class C
{

}

We want to serialize MainComplexObject, desired Json result:

{"$type":"ns.MyComplexObject, ...","Id":3,BList:[{"Id":85,"Name":"...","C":{...}]}

Only MainComplexObject type is written to Json. There is no type info except that.

Edit For @dbc 's comment:

All classed (MyComplexObject,B,C,..) have Interfaces.

NOTE

I want to deserialize it to correct type (MyComplexObject) also.

Oguz Karadenizli
  • 3,449
  • 6
  • 38
  • 73
  • do you mind sharing your code? What have you tried? – jpgrassi Jan 11 '16 at 11:00
  • You can use [`TypeNameHandling = TypeNameHandling.Auto`](http://www.newtonsoft.com/json/help/html/serializetypenamehandling.htm) to emit type information only when necessary, then to force type information for the *root object*, use the answer from [Serializing an interface/abstract object using NewtonSoft.JSON](https://stackoverflow.com/questions/28128923). – dbc Jan 11 '16 at 12:33
  • I've edited the question. could you check. – Oguz Karadenizli Jan 11 '16 at 13:14
  • Is it enough to serialize using `TypeNameHandling.Auto` then do `JsonConvert.SerializeObject(mainComplexObject, typeof(object), settings)` ? That will emit type information for the root object and not for nested objects *unless needed*. – dbc Jan 11 '16 at 21:31
  • Related or identical: [json.net - how to add property $type ONLY on root object](https://stackoverflow.com/questions/36356336). – dbc Apr 01 '16 at 17:14

0 Answers0