18/08/2017

Json.net also tricked me

Home



Recently, I was tricked by Roslyn, today by Json.NET. My bloody luck ;) Let's look at the following two very simple classes. Class A has one readonly property and I had to define a special constructor to allow Json.NET to set this property. B is also simple. It has one property, this time of type A with some default value.

public class A
{
   public string Name { get; }

   [JsonConstructor]
   public A(string name) { Name = name; }
}

public class B
{
   public A Test { get; set; } = new A("Default");

}
Now let's serialize an instance of B in the following way:
var serializedText = JsonConvert.SerializeObject(new B() { Test = new A("Fun") { } });
In the result, as expected, we will get the following text:

{"Test":{"Name":"Fun"}}

Now let's deserialize this string:
var result = (B)JsonConvert.DeserializeObject(serializedText, typeof(B));
Now question for 1 million dollars. What will be the value of A.Test.Name in a deserialized object. If you say Fun you are wrong! It will be Default!

I was surprised and I spent some time investigating this issue. Why did it happen? Well, it seems to me that when Json.NET creates a new object during deserialization and it notices that some property of this object is not null, them this default value will not be overriden. If it's a problem, there are at least 2 solutions:
  • Remove a default value for this property. It doesn't matter if it is set in a constructor of via a property initializer.
  • Add a special constructor. For instance, for class B it'll look as below. This constructor instructs Json.NET that Test property must be set even if a default value exists.
public class B
{
   public A Test { get; set; } = new A("Default");

   public B() {}

   [JsonConstructor]
   public B(A test) { Test = test; }
}


*The picture at the beginning of the post comes from own resources and shows elephants from Warsaw zoo.

25 comments:

Peter Lanoie said...

Isn't the problem much simpler than property construction? A.Name is written as read only. Whether the deserializer creates an instance of A to assign to B.Test or uses an existing instance (your "Default") is irrelevant. B.Test.Name is still read-only.

Peter Lanoie said...

So I re-read your post several times (I think all the As and Bs were confusing me). I think I jumped the gun on my first comment before I fully understood the solution. More importantly, I don't think I've used the JsonConstructor attribute so I didn't realize what it was accomplishing. I've typically solve the problem you describe by just making the properties read/write.

Michał Komorowski said...

@Peter Lanoie Thanks for the comment. Next time I will use more descriptive names for classes ;)

As to "making the properties read/write". It should help to make A.Name writable. However, it is not always possible.

jogibear9988 said...

I've ran into an issue with default values and Preserve References, see https://github.com/JamesNK/Newtonsoft.Json/issues/1351

Tyler Brinkley said...

Upon deserialization you should use var result = JsonConvert.DeserializeObject<B>(serializedText, new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace });

Michał Komorowski said...

@Tyler Brinkley - Thanks, I didn't know this one.

Omego2K said...

that did the trick for me. Anyway for it to not check the value before hand? Like in the case of a string property.

OpioidClinicsinjohnsonCityTN said...

Yeah, technology is going to change the business market of the world as it is getting better and better day by day and helping the business owners to get a big amount of profit form the business. By using technology, they can run the business easily without the difficulties."
sleep dentistry"

OpioidClinicsinjohnsonCityTN said...



I’m almost scared to admit this, but this year our kids don’t really have an official math curriculum. They are young-grade 5, grade 2, and K. We use technology, some worksheets, Life of Fred, a lot of manipulative, games, and a whole lot of real life. It has been going really well. And by the way, I am 100% sure that my oldest two hate math-they have told me a lot. For more click here

OpioidClinicsinjohnsonCityTN said...

Cool stuff you have and you keep overhaul every one of us
You have done a amazing job with you website.pokies online new zealand

OpioidClinicsinjohnsonCityTN said...



Everyone is busy making the world dirty, no one has time to think about our nature. They even don't realize without the green environment we'll be unable to survive. Everyone knows the truth but none of them are aware of it.Sonia Randhawa

OpioidClinicsinjohnsonCityTN said...

Hmm!! This blog is really cool, I’m so lucky that I have reached here and got this awesome information.Sonia Randhawa

OpioidClinicsinjohnsonCityTN said...

Definitely agree with the first tip because you have to make sure your home is ready before you list it in the market. Improvements are really important and staging as well will help in getting the best possible price when selling your home. After the improvements, it is also good to get a professional photographer to take photos of your home that will highlight the areas of your home and help to attract potential buyers. Awesome blog by the way and thanks for sharing.Sonia Randhawa

mohsin said...

Yes, this is the wonderful information that you shared with us. Investing with the help of equality funds is a very wonderful opportunity in real estate.Sonia Randhawa

OpioidClinicsinjohnsonCityTN said...

I throb people to realize just how affable this pay for an opinion is for your article. Its enticing, compelling content material. Your perspectives are much gone my personal getting into excuse to for this subject matter.Sonia Randhawa

OpioidClinicsinjohnsonCityTN said...

whoah this blog is great i love reading your articles. Keep up the great work! You know, a lot of people are hunting around for this info, you could aid them greatly.Manchester Market

OpioidClinicsinjohnsonCityTN said...

Our online courses are designed to help you build your future despite the hard times. We know what it feels like to want a better future but not know where to start. We are proud to be your starting place. Christine Sanni has built an award-winning career in technology; expanded her commitment and efforts towards environmental conservation; and is focused on helping others understand what makes them great. If you want to get the best place for online course visit Online learning sites

OpioidClinicsinjohnsonCityTN said...

Our online courses are designed without walls and without invisible ceilings. And that means irrespective of who you are, you're going to have access to it all. Nothing held back, just empowering content that will not only teach you what's possible but also make you powerful. Distance learning can give you an online education. For more visit learning

OpioidClinicsinjohnsonCityTN said...

Finding professionals is easy with Organic food Providers. Search our website to instantly connect with business and professionals. For professionals, our website works as a powerful tool for attracting more clients.

OpioidClinicsinjohnsonCityTN said...

Really interesting to read the story here shared and I feel special. The way the story presented also makes us more interesting. I'm looking forward to these kinds of the informative article and continue sharing more stories like this.izmir istanbul ucak bileti

OpioidClinicsinjohnsonCityTN said...

Fantastic guide again, this is the second post that I am reading at this blog. Loved it. I’m not a rental investor lover but got some ideas while reading your this post. Now, sharing your blog with my lovely twitter community.pegasus check in

OpioidClinicsinjohnsonCityTN said...

It's very useful blog post with informative and insightful content and i had good experience with this information.I have gone through CRS Info Solutions Home which really nice.turk hava yollari

Mike Johnson said...

I like elephants, they are so big and still. I have create instagram account about elephants and I have bought instagram followers from this site https://soclikes.com/buy-instagram-followers

OpioidClinicsinjohnsonCityTN said...


I definitely agree with the first tip because you have to make sure your home is ready before you list it in the market. Improvements are really important and staging as well will help in getting the best possible price when selling your home. After the improvements, it is also good to get a professional photographer to take photos of your home that will highlight the areas of your home and help to attract potential buyers. Awesome blog by the way and thanks for sharing.baby light head

julia said...

Investing online sounds so interesting! I would like to know some more details about investing in real estate online. It’s just hard to trust agents because sometimes they all seem to say the same things, it’s hard for us to know who’s telling you genuine information. read at simplecapacity

Post a comment