在处理原始类型时,有没有办法覆盖 Json.net 的默认反序列化行为?例如,当将 json 数组 [3.14,10,"test"]
反序列化为 object[]
的类型时,3.14 的类型将是 double
和 10 将是 long
类型.无论如何我可以拦截或覆盖这种类型决策,以便我可以将值分别反序列化为 decimal
和 int
?
Is there a way to override the default deserialization behaviour of Json.net when handling primitive types? For example when deserializing the json array [3.14,10,"test"]
to a type of object[]
3.14 will be of type double
and 10 will be of type long
. Is there anyway I can intercept or override this type decision so I could deserialize the values as decimal
and int
respectively?
我基本上总是希望 json 整数总是以 int
的形式返回,而浮点数则以 decimal
的形式返回.这将使我不必在我的代码中注入 double
到 decimal
转换.
I basically always want json integers to always return as int
and floats to return as decimal
. This will save me some having to inject double
to decimal
conversions in my code.
我已经研究过扩展 Newtonsoft.Json.Serialization.DefaultContractResolver
并实现我自己的 Newtonsoft.Json.JsonConverter
但我还没有发现任何方法来实现这个期望覆盖.
I've looked into extending Newtonsoft.Json.Serialization.DefaultContractResolver
and implementing my own Newtonsoft.Json.JsonConverter
but I have not discovered any way to implement this desired override.
重现的示例代码
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}
我想,这应该可行
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));
这篇关于覆盖 Json.Net 中的默认原始类型处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!