3

I'm attempting to get Json.NET to serialize an object and include it's type as follows...

    [JsonObject(ItemTypeNameHandling = TypeNameHandling.All)]
    public class ABC
    {
        public string Easy;
        public string As;
    }

...the following test...

        ABC abc = new ABC();
        abc.Easy = "123";
        abc.As = "do rey me";

        string output = JsonConvert.SerializeObject(abc);

...the output is...

{"Easy":"123","As":"do rey me"}

...I was hoping for...

{"$type":"MyTest+ABC, MyTest","Easy":"123","As":"do rey me"}

I'm trying to make selected contracts include type information in a Web API 2 project. Is there no other way to do this than setting it globally? Like so...

config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All
Mick
  • 6,527
  • 4
  • 52
  • 67
  • [`ItemTypeNameHandling`](http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonContainerAttribute_ItemTypeNameHandling.htm) *Gets or sets the type name handling used when serializing the collection's items*. It doesn't control type name handling for the type itself. Take a look at the answer to [SignalR Typenamehandling](https://stackoverflow.com/questions/32314638/signalr-typenamehandling/32404249#32404249) and at [Custom Json.NET serializer settings per type](https://stackoverflow.com/questions/17684925). Do either meet your needs? – dbc Jan 19 '16 at 16:07
  • Neither of those seem to be useful to me. I have a large number of types which I need to include types...and also large number I don't want types on. It may say ItemTypeNameHandling applies only to collections. yet ItemTypeNameHandling is a valid parameter on JsonObjectAttribute which is only valid on classes, structs and interfaces. I've not tested it but I'm guessing this would apply to all collections within the object. My work around is going to be to wrap the my objects I want to serialize types for in a collection – Mick Jan 20 '16 at 01:46
  • "I've not tested it but I'm guessing this would apply to all collections within the object" My guess is that if you test it you'll find that `ItemTypeNameHandling` applies only to collection properties, while `TypeNameHandling` may work the way you hope – Skym Jan 19 '17 at 11:42

1 Answers1

0

The solution I ended up using was to ensure such types are serialized in an array. So

ABC abc = new ABC();
abc.Easy = "123";
abc.As = "do rey me";
var package = new 
{
   Data = [] { abc }
};

string output = JsonConvert.SerializeObject(abcArray);

The resulting JSON contains the type of the object

{
   Data = [
       {"$type":"MyTest.ABC, MyTest","Easy":"123","As":"do rey me"}
   ]
}
Mick
  • 6,527
  • 4
  • 52
  • 67