JSON.NET-如何为存储在数组/列表中作为对象类型的原始C#类型包括类型名称处理 [英] JSON.NET - How do I include Type Name Handling for primitive C# types that are stored in an array/list as Object type

查看:142
本文介绍了JSON.NET-如何为存储在数组/列表中作为对象类型的原始C#类型包括类型名称处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Newtonsoft JSON.NET为我序列化/反序列化内容.但是我有一个列表,其中它们是Object类型:

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

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

当我将TypeNameHandling设置为TypeNameHandling.All进行序列化时,我期望它也会为列表中的每个实例提供一个$type,但事实并非如此.这是实际的输出:

When I serialize that with TypeNameHandling set to TypeNameHandling.All, I was expecting that it will also give a $type for each instance on the list but doesn't seem to be the case. Here is the actual output:

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

我需要为这些原始类型具有特定的类型名称处理,因为如果我将Int32值添加到列表中,并且在反序列化后返回时,JSON.NET会将其设置为Int64.这对我来说很重要,因为我正在尝试调用一些方法,并且为此我需要比较参数,并且它们必须具有相同的类型.您可以在JSON.NET中设置某种方法或设置来实现我所需要的吗?

I need this to have specific Type Name Handling for those primitive types because if I add an Int32 value in to the list and when it comes back after deserializing it JSON.NET sets it as Int64. That is a big deal for me because I am trying to invoke some methods and to do that I need to compare the parameters and they MUST have the same types. Is there a way or a setting you can set in JSON.NET to achieve what I need?

我已经看到了这条帖子,但是它是什么确实是他试图更改默认行为并总是返回Int32,这不是我想要的.

I've seen this post but what it does is that he is trying to change the default behavior and always return Int32 which is not what I'm looking for.

任何帮助将不胜感激.谢谢

Any help would be appreciated. Thanks

推荐答案

您可以为原始类型创建包装类,并根据需要包含隐式运算符:

You can create a wrapper class for primitive types, included 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 serialize 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"}]

这篇关于JSON.NET-如何为存储在数组/列表中作为对象类型的原始C#类型包括类型名称处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆