JSON.Net - Change $type field to another name?

json.net serialize object with root name
type specified in json was not resolved
json.net polymorphism
json net serialize type name
deserialization of reference types without parameterless constructor is not supported.
newtonsoft json
json.net strict deserialization
jsonconverter

When using Json.Net, I understand how to get the $type property into the rendered json, but is there a way to change that field name? I need to use "__type" instead of "$type".

Looks like this is hardcoded as public const string TypePropertyName = "$type"; in Newtonsoft.Json.Serialization.JsonTypeReflector which is internal static class unfortunately.

I needed this myself, and the only thing I can think of is having custom modified version of json.net itself. Which is of course is a major pita.

This sample uses JsonPropertyAttribute to change the names of properties when they Types. Copy. public class Videogame { [JsonProperty("name")] public string Videogame starcraft = new Videogame { Name = "Starcraft", ReleaseDate  When using Json.Net, I understand how to get the $type property into the rendered json, but is there a way to change that field name? I need to use "__type" instead

http://json.codeplex.com/workitem/22429

"I would rather keep $type hard coded and consistent."

Consistent with what I wonder?

http://json.codeplex.com/workitem/21989

I would rather not - I think this is too specific to me and I don't want to go overboard with settings. At some point I will probably implement this - http://json.codeplex.com/workitem/21856 - allowing people to read/write there own meta properties in the JSON and you could reimplement type name handling with a new property name. The other option is just to modify the source code for yourself to have that property name.

And more recently, Issue #36: Customizable $type property name feature:

I'd rather not

This is my solution...

json.Replace("\"$type\": \"", "\"type\": \"");

Json.TypeNameHandling setting to include type information when serializing JSON Businesses = new List<Business> { new Hotel { Name = "Hudson Hotel",​  Json.Net-Serialize property name without quotes ; How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects? How can I change property names when serializing with Json.net? Ignoring null fields in Json.net

when serializing, there is a nice way to override the property name:

public class CustomJsonWriter : JsonTextWriter
{
    public CustomJsonWriter(TextWriter writer) : base(writer)
    {
    }

    public override void WritePropertyName(string name, bool escape)
    {
        if (name == "$type") name = "__type";
        base.WritePropertyName(name, escape);
    }
}

var serializer = new JsonSerializer();
var writer = new StreamWriter(stream) { AutoFlush = true };
serializer.Serialize(new CustomJsonWriter(writer), objectToSerialize);

I haven't tried deserialization yet, but in worst case I could use:

json.Replace("\"__type": \"", "\"type\": \"$type\");

NET object models or other code changes. Deserialize JSON null literal to non-​nullable value types, ⚠️ Not supported, workaround, Json does case-​insensitive property name matching by default. A non-string value received for a string field results in a JsonException with the following message:. Thankfully JSON.NET allows for a lot of flexibility in how JSON objects are deserialize. I have written two blog posts on this before. To handle this particular scenario, I created a JsonConverter with a simple mapping table which maps the attributes of the second JSON payload to the attributes of the first JSON payload.

I had to do this for my UI REST API as Angular.js disregards fields names starting with a dollar sign ($).

So here's a solution that renames $type to __type for the whole Web API and works both for serialization and deserialization.

In order to be able to use a custom JsonWriter and a custom JsonReader (as proposed in the other answers to this question), we have to inherit the JsonMediaTypeFormatter and override the corresponding methods:

internal class CustomJsonNetFormatter : JsonMediaTypeFormatter
{
    public override JsonReader CreateJsonReader(Type type, Stream readStream, Encoding effectiveEncoding)
    {
        return new CustomJsonReader(readStream, effectiveEncoding);
    }

    public override JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encoding effectiveEncoding)
    {
        return new CustomJsonWriter(writeStream, effectiveEncoding);
    }

    private class CustomJsonWriter : JsonTextWriter
    {
        public CustomJsonWriter(Stream writeStream, Encoding effectiveEncoding)
            : base(new StreamWriter(writeStream, effectiveEncoding))
        {
        }

        public override void WritePropertyName(string name, bool escape)
        {
            if (name == "$type") name = "__type";
            base.WritePropertyName(name, escape);
        }
    }

    private class CustomJsonReader : JsonTextReader
    {
        public CustomJsonReader(Stream readStream, Encoding effectiveEncoding)
            : base(new StreamReader(readStream, effectiveEncoding))
        {
        }

        public override bool Read()
        {
            var hasToken = base.Read();
            if (hasToken && TokenType == JsonToken.PropertyName && Value != null && Value.Equals("__type"))
            {
                SetToken(JsonToken.PropertyName, "$type");
            }
            return hasToken;
        }
    }
}

Of course you need to register the custom formatter in your WebApiConfig. So we replace the default Json.NET formatter with our custom one:

config.Formatters.Remove(config.Formatters.JsonFormatter);
config.Formatters.Add(new CustomJsonNetFormatter());

Done.

Json namespace has built-in converters for most primitive types that map to throw new JsonException( $"Unable to convert \"{propertyName}\" to Enum public class Person { public string Name { get; set; } } public class  This sample uses T:Newtonsoft.Json.JsonPropertyAttribute to change the names of properties when they are serialized to JSON.

We had a need for this so I created a custom JsonReader. We're are using rest in our MS web services with complex data models and needed to replace the "__type" property with "$type."

class MSJsonReader : JsonTextReader
{
    public MSJsonTextReader(TextReader reader) : base(reader) { }

    public override bool Read()
    {
        var hasToken = base.Read();

        if (hasToken && base.TokenType == JsonToken.PropertyName && base.Value != null && base.Value.Equals("__type"))
            base.SetToken(JsonToken.PropertyName, "$type");

        return hasToken;
    }
}

Here is how we use it.

using(JsonReader jr = new MSJsonTextReader(sr))
{
    JsonSerializer s = new JsonSerializer();
    s.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
    s.NullValueHandling = NullValueHandling.Ignore;
    s.TypeNameHandling = TypeNameHandling.Auto; // Important!
    s.Binder = new MSRestToJsonDotNetSerializationBinder("Server.DataModelsNamespace", "Client.GeneratedModelsNamespace");

    T deserialized = s.Deserialize<T>(jr);

    return deserialized;
}

Here is our MSRestToJsonDotNetSerializationBinder that completes the compatibility between MS rest and Json.Net.

class MSRestToJsonDotNetSerializationBinder : System.Runtime.Serialization.SerializationBinder
{
    public string ServiceNamespace { get; set; }
    public string LocalNamespace { get; set; }

    public MSRestToJsonDotNetSerializationBinder(string serviceNamespace, string localNamespace)
    {
        if (serviceNamespace.EndsWith("."))
            serviceNamespace = serviceNamespace.Substring(0, -1);

        if(localNamespace.EndsWith("."))
            localNamespace = localNamespace.Substring(0, -1);

        ServiceNamespace = serviceNamespace;
        LocalNamespace = localNamespace;
    }

    public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
    {
        assemblyName = null;
        typeName = string.Format("{0}:#{1}", serializedType.Name, ServiceNamespace); // MS format
    }

    public override Type BindToType(string assemblyName, string typeName)
    {
        string jsonDotNetType = string.Format("{0}.{1}", LocalNamespace, typeName.Substring(0, typeName.IndexOf(":#")));
        return Type.GetType(jsonDotNetType);
    }
}

Emit to generate efficient formatters for serializing types that it sees. This change is preferred for allocation and performance reasons. NET serializer in 6​.x, JSON object field names would attempt to be matched with C# POCO Another serializer also exists within NEST known as the RequestResponseSerializer . Jackson. If you are using Jackson, then you can use the @JsonProperty annotation to customize the name of a given JSON property.. Therefore, you just have to annotate the entity fields with the @JsonProperty annotation and provide a custom JSON property name, like this:

Json: Dynamically rename or ignore properties without changing the serialized class toolchain: A Swagger specification uses JSON Schemas to describe types, but it is I had to ignore or rename properties in the Swagger serializer. Another use case of this contract resolver is, if you want to conditionally  This quick tutorial illustrates how to change the name of a field to map to another JSON property on serialization. If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial.

<typeparam name="T">The object type to convert. ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) throw new JsonSerializationException("Could not determine object type. It is very problematic to use JSON.NET for deserialization GraphQL responses with interfaces fields because GraphQL uses __typename field discriminator. In my opinion the choice of a constant for a discriminator is a short-sighted decision.

By specifying that all type names should be included in the serialized Or perhaps you want to change the "Programming" class to be the "Coding" class. JsonSerializer serializer) { // Variables. var fields = new List(); var  Display Name - You can change the display name as many times as you want. Best example to understand internal name is "Modified By" field which is having internal name "Editor". When you edit the column name and change it to something totally different, the internal name doesn't change. But why should we care? Well, Because:

Comments
  • I need this too, for example JSON-LD uses @type
  • Unfortunately, I have pretty much had to completely abandon the path I was headed down because of how hard Json.Net is to use in many cases. This is just one example.
  • I am myself looking of how I on the server-side, that is written i C# and uses Json.NET, can deserialize JSON sent from an Android app using Jackson. In Jackson I can setup to use "$type", but it doesnt work anyway.
  • Your solution is awesome! ^_^
  • I like this solution! With a small customization I no longer have to use the lengthy types names Namespace.Type, AssemblyName but can also rewrite this ;-)
  • I don't see how deserializing will determine the correct type with your solution. Can you explain?
  • To deserialize, try JsonCreationConverter, e.g. see stackoverflow.com/questions/8030538