确定是数组还是对象

本文关键字:对象 数组 | 更新日期: 2024-09-21 13:07:23

我创建了一个类来解析JSON响应。我遇到的问题是,一个项目有时是数组,另一个项目是对象。我试着想出一个变通办法,但它总是给我带来一些其他问题。

我想要一些if或try语句,让我确定创建了什么。

伪代码。。。

    [DataContract]
    public class Devices
    {   
        if(isArray){
        [DataMember(Name = "device")]
        public Device [] devicesArray { get; set; }}
        else{
        [DataMember(Name = "device")]
        public Device devicesObject { get; set; }}
    }

使用Dan的代码,我提出了以下解决方案,但现在当我尝试使用它时,我遇到了选角问题。"无法将类型为System.object的对象强制转换为类型为MItoJSON.Device"

[DataContract]
    public class Devices
    {
        public object target;
        [DataMember(Name = "device")]
        public object Target
        {
            get { return this.target; }
            set
            {
                this.target = value;
                var array = this.target as Array;
                this.TargetValues = array ?? new[] { this.target };
            }
        }
        public Array TargetValues { get; private set; }
    }

确定是数组还是对象

将目标属性声明为对象。然后,您可以创建一个助手属性来处理目标是数组还是单个对象:

    private object target;
    public object Target
    {
        get { return this.target; }
        set
        {
            this.target = value;
            var array = this.target as Array;
            this.TargetValues = array ?? new[] { this.target };
        }
    }
    public Array TargetValues { get; private set; }