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 6084145
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T11:29:13+00:00 2026-05-23T11:29:13+00:00

I’m using JSON.NET to serialize some of my objects, and i’d like to know

  • 0

I’m using JSON.NET to serialize some of my objects, and i’d like to know if there is a simple way to override the default json.net converter only for a specific object?

Currently I have the following class:

public class ChannelContext : IDataContext
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<INewsItem> Items { get; set; }
}

JSON.NET currently serializes the above like:

{
    "Id": 2,
    "Name": "name value",
    "Items": [ item_data_here ]
}

Is it possible just for that specific class to format it this way instead:

"Id_2":
{
    "Name": "name value",
    "Items": [ item data here ]
}

I’m kinda new to JSON.NET.. I was wondering if the above has something to do with writing a custom converter. I wasn’t able to find any concrete examples on how to write one, If anyone can point me out to a specific source, I’ll really appreciate it.

I need to find a solution which makes that specific class always convert the same, because the above context is a part of an even bigger context which the JSON.NET default converter converts just fine.

Hope my question is clear enough…

UPDATE:

I’ve found how to create a new custom converter (by creating a new class which inherits from JsonConverter and override it’s abstract methods), I overriden the WriteJson method as follows:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        ChannelContext contextObj = value as ChannelContext;

        writer.WriteStartObject();
        writer.WritePropertyName("id_" + contextObj.Id);
        writer.WriteStartObject();
        writer.WritePropertyName("Name");
        serializer.Serialize(writer, contextObj.Name);

        writer.WritePropertyName("Items");
        serializer.Serialize(writer, contextObj.Items);
        writer.WriteEndObject();
        writer.WriteEndObject();
    }

This indeed does the job successfully, but…
I’m intrigued if there’s a way to serialize the rest of the object properties by reusing the default JsonSerializer (or converter for that matter) instead of manually “Writing” the object using the jsonwriter methods.

UPDATE 2:
I’m trying to get a more generic solution and came up with the following:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteStartObject();

        // Write associative array field name
        writer.WritePropertyName(m_FieldNameResolver.ResolveFieldName(value));

        // Remove this converter from serializer converters collection
        serializer.Converters.Remove(this);

        // Serialize the object data using the rest of the converters
        serializer.Serialize(writer, value);

        writer.WriteEndObject();
    }

This works fine when adding the converter manually to the serializer, like this:

jsonSerializer.Converters.Add(new AssociativeArraysConverter<DefaultFieldNameResolver>());
jsonSerializer.Serialize(writer, channelContextObj);

But doesn’t work when using the [JsonConverter()] attribute set to my custom coverter above the ChannelContext class because of a self reference loop that occurs when executing:

serializer.Serialize(writer, value)

This is obviously because my custom converter is now considered the default converter for the class once it is set with the JsonConverterAttribute, so I get an inifinite loop.
The only thing I can think of, in order to solve this problem is inheriting from a basic, jsonconverter class, and calling the base.serialize() method instead…
But is such a JsonConverter class even exists?

Thanks a lot!

Mikey

  • 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-05-23T11:29:13+00:00Added an answer on May 23, 2026 at 11:29 am

    If anyone’s interested in my solution:

    When serializing certain collections, I wanted to create an associative json array instead of a standard json array, so my colleague client side developer can reach those fields efficiently, using their name (or key for that matter) instead of iterating through them.

    consider the following:

    public class ResponseContext
    {
        private List<ChannelContext> m_Channels;
    
        public ResponseContext()
        {
            m_Channels = new List<ChannelContext>();
        }
    
        public HeaderContext Header { get; set; }
    
        [JsonConverter(
            typeof(AssociativeArraysConverter<ChannelContextFieldNameResolver>))]
        public List<ChannelContext> Channels
        {
            get { return m_Channels; }
        }
    
    }
    
    [JsonObject(MemberSerialization = MemberSerialization.OptOut)]
    public class ChannelContext : IDataContext
    {
        [JsonIgnore]
        public int Id { get; set; }
    
        [JsonIgnore]
        public string NominalId { get; set; }
    
        public string Name { get; set; }
    
        public IEnumerable<Item> Items { get; set; }
    }
    

    Response context contains the whole response which is written back to the client, like you can see, it includes a section called “channels”, And instead of outputting the channelcontexts in a normal array, I’d like to be able to output in the following way:

    "Channels"
    {
    "channelNominalId1":
    {
      "Name": "name value1"
      "Items": [ item data here ]
    },
    "channelNominalId2":
    {
      "Name": "name value2"
      "Items": [ item data here ]
    }
    }
    

    Since I wanted to use the above for other contexts as well, and I might decide to use a different property as their “key”, or might even choose to create my own unique name, which doesn’t have to do with any property, I needed some sort of a generic solution, therefore I wrote a generic class called AssociativeArraysConverter, which inherits from JsonConverter in the following manner:

    public class AssociativeArraysConverter<T> : JsonConverter
        where T : IAssociateFieldNameResolver, new()
    {
        private T m_FieldNameResolver;
    
        public AssociativeArraysConverter()
        {
            m_FieldNameResolver = new T();
        }
    
        public override bool CanConvert(Type objectType)
        {
            return typeof(IEnumerable).IsAssignableFrom(objectType) &&
                    !typeof(string).IsAssignableFrom(objectType);
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            IEnumerable collectionObj = value as IEnumerable;
    
            writer.WriteStartObject();
    
            foreach (object currObj in collectionObj)
            {
                writer.WritePropertyName(m_FieldNameResolver.ResolveFieldName(currObj));
                serializer.Serialize(writer, currObj);
            }
    
            writer.WriteEndObject();
        }
    }
    

    And declared the following Interface:

    public interface IAssociateFieldNameResolver
    {
        string ResolveFieldName(object i_Object);
    }
    

    Now all is left to do, is create a class which implements IAssociateFieldNameResolver’s single function, which accepts each item in the collection, and returns a string based on that object, which will act as the item’s associative object’s key.

    Example for such a class is:

    public class ChannelContextFieldNameResolver : IAssociateFieldNameResolver
    {
        public string ResolveFieldName(object i_Object)
        {
            return (i_Object as ChannelContext).NominalId;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm making a simple page using Google Maps API 3. My first. One marker
I have some data like this: 1 2 3 4 5 9 2 6
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I would like to count the length of a string with PHP. The string
I am reading a book about Javascript and jQuery and using one of the

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.