3

I have a really simple struct like this.

[Serializable]
public struct Pair<T, K> {

  public T First { get; private set; }
  public K Second { get; private set; }

  public Pair(T first, K second) {
    First = first;
    Second = second;
  }

  ...
}

Let's say I have a Pair<double, double> instance. Serialization works fine, and I get the expected {First:5.0,Second:10.0} for example.

But whenever I try to deserialize, I get the default value of {0; 0}. When I add the JsonConstructor attribute to the constructor, everything works as expected.

I would have expected that Json.NET is able to find the constructor by convention in such simple cases, but it seems like no. If there is any other way, I would like to avoid adding this attribute because that would introduce a dependency on Json.NET in this lower-level kind of util library.

Is there any way to do this properly without the JsonConstructor attribute and also without having to write tons of custom value converter code?

Note 1

I'm aware of the built-in Tuple types and I'm also guessing that those are supported natively. In this case I have an older codebase which uses this struct quite a lot, so I have no way to use Tuple currently.

Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93
  • The problem has nothing to do with the fact it is a `struct`. It is because your struct has no default constructor. Typically I would add a private default constructor for deserialization. NB This problem exists for ALL serialization libraries. – Aron Feb 25 '16 at 01:29
  • @Aron the only thing it has to do with being a struct is that it silently failed because structs automatically have a default constructor. I actually disagree about this question being a duplicate of that one because I stated that I know about `JsonConstructor` attribut, and my main question was if I can somehow teach Json.NET to search for the "best" constructor by convention. Now I have to choose from two bad things: adding the attribute and introduce dependency; or implementing a converter and maintain it to ensure it is always used. – Zoltán Tamási Feb 25 '16 at 06:30
  • Collaborators, could you please reopen this question as I think it's not an exact duplicate. I've added my answer to the question which you've referred, but I think it doesn't exactly belong there and would be better suited here as it answers my exact question. – Zoltán Tamási Mar 08 '16 at 10:41

0 Answers0