JSON.NET How to enable type name processing for C # primitive types that are stored in an array / list as an object type

I am using Newtonsoft JSON.NET to serialize / deserialize for me. But I have this list in which they are of type Object :

 var list = new List<Object>() { "hi there", 1, 2.33 }; 

When I serialize this with TypeNameHandling set to TypeNameHandling.All , I expected it to also give $type for each instance in the list, but it doesn't seem to be that way. Here is the actual conclusion:

 { "$type": "System.Collections.Generic.List`1[[System.Object, mscorlib]], mscorlib", "$values": [ "hi there", 1, 2.33 ] } 

I need that I have a specific type name processing for these primitive types, because if I add an Int32 value to the list, and when it comes back after deserialization, JSON.NET sets it to Int64 . This is very important for me, because I'm trying to call some methods and do this, I need to compare the parameters, and they MUST have the same types. Is there a way or settings that you can set in JSON.NET to achieve what I need?

I saw this post , but it does that it tries to change the default behavior and always returns Int32 , which is not what I'm looking for.

Any help would be greatly appreciated. Thanks

+5
source share
1 answer

You can create a wrapper class for primitive types, including implicit operators, as you want:

 class TypeWrapper { public object Value { get; set; } public string Type { get; set; } public static implicit operator TypeWrapper(long value) { return new TypeWrapper { Value = value, Type = typeof(long).FullName }; } public static implicit operator long(TypeWrapper value) { return (long)value.Value; } public static implicit operator TypeWrapper(int value) { return new TypeWrapper { Value = value, Type = typeof(int).FullName }; } public static implicit operator int(TypeWrapper value) { return (int)value.Value; } } 

Then you will have element types when serializing data:

 var data = new List<TypeWrapper> { 1, 2L }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(data); Console.WriteLine(json); // result: [{"Value":1,"Type":"System.Int32"},{"Value":2,"Type":"System.Int64"}] 
+1
source

Source: https://habr.com/ru/post/1243721/


All Articles