Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9140637
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T09:32:32+00:00 2026-06-17T09:32:32+00:00

I have an object with a list of base class sub-objects. Sub-objects need a

  • 0

I have an object with a list of base class sub-objects. Sub-objects need a custom converter. I can’t make my custom converter respect ItemTypeNameHandling option.

Sample code (create a new C# Console project, add JSON.NET NuGet package):

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace My {
    class Program {
        private static void Main () {
            Console.WriteLine(JsonConvert.SerializeObject(
                new Box { toys = { new Spintop(), new Ball() } },
                Formatting.Indented));
            Console.ReadKey();
        }
    }

    [JsonObject] class Box
    {
        [JsonProperty (
            ItemConverterType = typeof(ToyConverter),
            ItemTypeNameHandling = TypeNameHandling.Auto)]
        public List<Toy> toys = new List<Toy>();
    }
    [JsonObject] class Toy {}
    [JsonObject] class Spintop : Toy {}
    [JsonObject] class Ball : Toy {}

    class ToyConverter : JsonConverter {
        public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) {
            serializer.Serialize(writer, value);
        }
        public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
            return serializer.Deserialize(reader, objectType);
        }
        public override bool CanConvert (Type objectType) {
            return typeof(Toy).IsAssignableFrom(objectType);
        }
    }
}

Produced output:

{
  "toys": [
    {},
    {}
  ]
}

Necessary output (this is what happens if I comment ItemConverterType = typeof(ToyConverter), line):

{
  "toys": [
    {
      "$type": "My.Spintop, Serialization"
    },
    {
      "$type": "My.Ball, Serialization"
    }
  ]
}

I’ve tried temporarily changing value of serializer.TypeNameHandling in ToyConverter.WriteJson method, but it affects unrelated properties. (Of course, my real converter is more complex than that. It’s just an example with base functionality.)

Question: How to make my custom JsonConverter respect ItemTypeNameHandling property of JsonProperty attribute?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T09:32:33+00:00Added an answer on June 17, 2026 at 9:32 am

    Having delved into the source code for Json.Net (version 4.5 release 11), it looks as though what you want to do is not possible.

    The key to getting types written to the output is this method:

    Newtonsoft.Json.Serialization.JsonSerializerInternalWriter
        .ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract,
            JsonProperty member, JsonContainerContract containerContract,
            JsonProperty containerProperty)
    

    It’s the containerContract and containerProperty parameters that are important here. When serializing without a converter, these parameters are supplied and ShouldWriteType is able to use them to figure out what TypeNameHandling to use.

    When serializing with a converter, however, those two parameters are not supplied. This appears to be because ToyConverter.WriteJson results in a call to Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue like this:

    SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null);
    

    Note that the last two parameters are in fact a JsonContainerContract containerContract and JsonProperty containerProperty, and are passed down the chain to the ShouldWriteType method. Therein lies the problem: because they are null, the logic of the ShouldWriteType method means that it returns false, thus the type is not written.

    Edit:

    Inspired by this, you could workaround this problem by customising the WriteJson method of your converter:

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteStartObject();
        writer.WritePropertyName("$type");
        writer.WriteValue(RemoveAssemblyDetails(value.GetType().AssemblyQualifiedName.ToString()));
        writer.WriteEndObject();
    }
    
    private static string RemoveAssemblyDetails(string fullyQualifiedTypeName)
    {
        StringBuilder builder = new StringBuilder();
    
        // loop through the type name and filter out qualified assembly details from nested type names
        bool writingAssemblyName = false;
        bool skippingAssemblyDetails = false;
        for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
        {
            char current = fullyQualifiedTypeName[i];
            switch (current)
            {
                case '[':
                    writingAssemblyName = false;
                    skippingAssemblyDetails = false;
                    builder.Append(current);
                    break;
                case ']':
                    writingAssemblyName = false;
                    skippingAssemblyDetails = false;
                    builder.Append(current);
                    break;
                case ',':
                    if (!writingAssemblyName)
                    {
                        writingAssemblyName = true;
                        builder.Append(current);
                    }
                    else
                    {
                        skippingAssemblyDetails = true;
                    }
                    break;
                default:
                    if (!skippingAssemblyDetails)
                        builder.Append(current);
                    break;
            }
        }
    
        return builder.ToString();
    }
    

    Note that that RemoveAssemblyDetails method is ripped straight from the Json.Net source.

    You will of course need to modify the WriteJson method to output the rest of the fields, but hopefully that does the trick.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a base class which has an embedded List that can be used
Say, I have a fonction that operates a list of base objects. But I
I have an object in a list that I need to rank several different
I have class A with a public std::list<int> object list_ . Class B ,
I have a list of base objects (RTUDevice) and want to iterate through and
I have a base class like this: class base(object): name = def __init__(self,name): self.user
I have the following class: class Tileset { //base class public: static std::vector<Tileset*> list;
I have BaseClass List Public Class Package <XmlElement(OBJECT)> Public List As List(Of baseobj) Public
I have the following code. My intention that this custom object can be cast
Given a list of classes inheriting from this base: class Plugin(object): run_after_plugins = ()

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.