Realeyes Realeyes - 8 months ago 42
C# Question

How to forbid Json.Net to convert ints to bools for deserialization

public class RootobjectTest
public int timestamp { get; set; }
public string Base { get; set; }
public Rates rates { get; set; }

public class Rates
public float AED { get; set; }
public float AFN { get; set; }
public float ALL { get; set; }
public float AMD { get; set; }
public float YER { get; set; }
public float ZAR { get; set; }
public float ZMK { get; set; }
public float ZMW { get; set; }
public float ZWL { get; set; }

var jsonData = @"{ ""timestamp"": 1370340068, ""base"": ""USD"", ""rates"": {
3.672958, ""AFN"": 54.154801, ""ALL"": 107.66425, ""AMD"": 419.62875,
""YER"": 214.964253, ""ZAR"": 9.813218, ""ZMK"": 5227.108333, ""ZMW"": 5.344453,
""ZWL"": 322.387247 }}";

var currencyRates = JsonConvert.DeserializeObject<RootobjectTest>(jsonData);

All is good and works perfectly. But if I change

public int timestamp { get; set; }


public bool timestamp { get; set; }

I don't get any errors. Json.Net parses int value of timestamp and converts it to bool. Is there elegant and simple way to forbid this?


Making Json.Net strict would require quite a bit of work, but it can probably be done (you'll have to implement custom strict JsonConverters for all types you need). Official position of the library's author is to use JSON schemas for validation.

I wouldn't worry about validation too much though, unless it actually becomes an issue. There're a lot of dynamically typed languages out there which convert variable types any way they want, and people somehow manage to use them effeciently. :) Json.Net folows the same philosophy.