2

I have in mind the issues with serializing Int32 and getting Int64 while deserializing. My problem is more general, I have an array of objects which can hold Int32 next to Int64.

So I cannot write custom converter on deserialization and blindly assume everything is Int32/Int64.

How to handle serialization/deserialization in such case?

astrowalker
  • 3,123
  • 3
  • 21
  • 40
  • Are those occurrences of Int32 predictable? – Dominique Lorre Sep 12 '16 at 08:59
  • Looks similar to [JSON.net (de)serialize untyped property](https://stackoverflow.com/questions/38777588/json-net-deserialize-untyped-property). – dbc Sep 12 '16 at 09:01
  • @DominiqueLorre, no, not at all. – astrowalker Sep 12 '16 at 09:06
  • @dbc, thank you (unfortunately I cannot upvote comment). There is one hop to make now -- how to bind converter per each element of the array. Or worse solution hardcode the name of the property with an array and then manually convert back and forth each element. – astrowalker Sep 12 '16 at 09:27

1 Answers1

0

You can use the UntypedToTypedValueConverter from JSON.net (de)serialize untyped property, with one difference - you need to apply it to the array items rather than the array itself using [JsonProperty(ItemConverterType = typeof(UntypedToTypedValueConverter))], e.g.:

public class RootObject
{
    [JsonProperty(ItemConverterType = typeof(UntypedToTypedValueConverter))]
    public object [] Items { get; set; }
}

This applies the converter to the entries in the array rather than to the array itself. Then serialize and deserialize with JsonSerializerSettings.TypeNameHandling = TypeNameHandling.Auto, e.g.:

var root = new RootObject { Items = new object[] { 1, 1L, int.MaxValue, long.MaxValue } };
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto };
var json = JsonConvert.SerializeObject(root, settings);
var root2 = JsonConvert.DeserializeObject<RootObject>(json, settings);

Sample fiddle.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • Thank you very much, this is embarrassing though, because even in simplest case (as above), I get back all the values wrapped. For now I cannot tell why but `WriteJson` is called as you would expect but `ReadJson` is completely ignored. I look and look and don't see why it is ignored. – astrowalker Sep 12 '16 at 10:50
  • @astrowalker - I added a sample [fiddle](https://dotnetfiddle.net/FPdg5B). – dbc Sep 12 '16 at 11:12
  • Thank you, finally found it! If you add explicit constructor for `RootObject` taking array of objects, and setting `Items` the method `ReadJson` will **not** be called. Once again thank you very much! (I put upvotes, but they are not visible). – astrowalker Sep 12 '16 at 11:24