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

  • Home
  • SEARCH
  • 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 6870901
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T03:44:23+00:00 2026-05-27T03:44:23+00:00

I have approximately the following picture: public class Foo { public Foo(Bar bar, String

  • 0

I have approximately the following picture:

public class Foo
{
   public Foo(Bar bar, String x, String y)
   {
       this.Bar = bar;
       this.X = x;
       this.Y = y;
   }

   [JsonIgnore]
   public Bar Bar { get; private set; }

   public String X { get; private set; }
   public String Y { get; private set; }
}

public class Bar
{
    public Bar(String z)
    {
        this.Z = z;
    }

    public String Z { get; private set; }
}

I want somehow to pass an object of type Bar to a constructor of type Foo during deserialization, i.e:

var bar = new Bar("Hello world");
var x = JsonConvert.DeserializeObject<Foo>(fooJsonString, bar);
  • 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-27T03:44:24+00:00Added an answer on May 27, 2026 at 3:44 am

    Here are my thoughts regarding problem solution:

    The problem:

    Json.Net’s custom deserialization api is not transparent, i.e. affects my class hierarchy.

    Actually it’s not a problem in case when you have 10-20 classes in your project, though if you have huge project with thousands of classes, you are not particularly happy about the fact that you need comply your OOP design with Json.Net requirements.

    Json.Net is good with POCO objects which are populated (initialized) after they are created. But it’s not truth in all cases, sometimes you get your objects initialized inside constructor. And to make that initialization happen you need to pass ‘correct’ arguments. These ‘correct’ arguments can either be inside serialized text or they can be already created and initialized some time before. Unfortunately Json.Net during deserialization passes default values to arguments that he doesn’t understand, and in my case it always causes ArgumentNullException.

    The solution:

    Here is approach that allows real custom object creation during deserialization using any set of arguments either serialized or non-serialized, the main problem is that the approach sub-optimal, it requires 2 phases of deserialization per object that requires custom deserialization, but it works and allows deserializing objects the way you need it, so here goes:

    First we reassemble the CustomCreationConverter class the following way:

    public class FactoryConverter<T> : Newtonsoft.Json.JsonConverter
    {
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotSupportedException("CustomCreationConverter should only be used while deserializing.");
        }
    
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
    
            T value = CreateAndPopulate(objectType, serializer.Deserialize<Dictionary<String, String>>(reader));
    
            if (value == null)
                throw new JsonSerializationException("No object created.");
    
            return value;
        }
    
        /// <summary>
        /// Creates an object which will then be populated by the serializer.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns></returns>
        public abstract T CreateAndPopulate(Type objectType, Dictionary<String, String> jsonFields);
    
        /// <summary>
        /// Determines whether this instance can convert the specified object type.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>
        ///     <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
        /// </returns>
        public override bool CanConvert(Type objectType)
        {
            return typeof(T).IsAssignableFrom(objectType);
        }
    
        /// <summary>
        /// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
        /// </value>
        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }
    }
    

    Next we create the factory class that will create our Foo:

    public class FooFactory : FactoryConverter<Foo>
    {
        public FooFactory(Bar bar)
        {
            this.Bar = bar;
        }
    
        public Bar Bar { get; private set; }
    
        public override Foo Create(Type objectType, Dictionary<string, string> arguments)
        {
            return new Foo(Bar, arguments["X"], arguments["Y"]);
        }
    }
    

    Here is sample code:

    var bar = new Bar("BarObject");
    
    var fooSrc = new Foo
    (
        bar,
        "A", "B"
    );
    
    var str = JsonConvert.SerializeObject(fooSrc);
    
    var foo = JsonConvert.DeserializeObject<Foo>(str, new FooFactory(bar));
    
    Console.WriteLine(str);
    

    In this case foo contains an argument that we needed to pass to a Foo constructor during deserialization.

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

Sidebar

Related Questions

I have a simple service that does approximately the following: An HTTP client connects
I have the following query: SELECT MAX([LastModifiedTime]) FROM Workflow There are approximately 400M rows
I have a reasonably large set of phone numbers (approximately 2 million) in a
I have the following problem. I have a set of elements that I can
I want to change the width of elements rendered using following code. I have
Take the following code snippit: f = open(/mnt/remoteserver/bar/foo.bin, O_RDONNLY); while (true) { byteseread =
I have a MySQL table with approximately 3000 rows per user. One of the
I have large database table, approximately 5GB, now I wan to getCurrentSnapshot of Database
I have 7-8 xml files. Each one is approximately 50 MB in size. What
In my work I have with great results used approximate string matching algorithms such

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.