Overriding the handling of default primitives in Json.Net

Is there a way to override the default Json.net deserialization behavior when handling primitive types? For example, when deserializing a json array [3.14,10,"test"]for type object[]3.14 will have a type double, and 10 will have a type long. In any event I can intercept or override this type of decision, so that I can deserialize the value as decimaland intrespectively?

Basically, I always want json integers to always return like intand float to return as decimal. This will save me from having to type doublein decimalconversions in my code.

I looked at expanding Newtonsoft.Json.Serialization.DefaultContractResolverand implementing my own Newtonsoft.Json.JsonConverter, but I did not find a way to implement this required override.

Sample code to play

object[] variousTypes = new object[] {3.14m, 10, "test"};
string jsonString = JsonConvert.SerializeObject(variousTypes);
object[] asObjectArray = JsonConvert.DeserializeObject<object[]>(jsonString); // Contains object {double}, object {long}, object {string}
+5
source share
1 answer

I think it should work

public class MyReader : JsonTextReader
{
    public MyReader(string s) : base(new StringReader(s))
    {
    }

    protected override void SetToken(JsonToken newToken, object value)
    {
        object retObj = value;
        if (retObj is long) retObj = Convert.ChangeType(retObj, typeof(int));
        if (retObj is double) retObj = Convert.ChangeType(retObj, typeof(decimal));

        base.SetToken(newToken, retObj);
    }
}


object[] variousTypes = new object[] { 3.14m, 10, "test" };
string jsonString = JsonConvert.SerializeObject(variousTypes);

JsonSerializer serializer = new JsonSerializer();
var asObjectArray = serializer.Deserialize<object[]>(new MyReader(jsonString));
+1
source

All Articles