覆盖 Json.Net 中的默认原始类型处理

Overriding Default Primitive Type Handling in Json.Net(覆盖 Json.Net 中的默认原始类型处理)
本文介绍了覆盖 Json.Net 中的默认原始类型处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理原始类型时,有没有办法覆盖 Json.net 的默认反序列化行为?例如,当将 json 数组 [3.14,10,"test"] 反序列化为 object[] 的类型时,3.14 的类型将是 double10 将是 long 类型.无论如何我可以拦截或覆盖这种类型决策,以便我可以将值分别反序列化为 decimalint?

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 的形式返回.这将使我不必在我的代码中注入 doubledecimal 转换.

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 中的默认原始类型处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)