2

我创建了一个类来解析 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; }
    }
4

1 回答 1

1

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

    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; }
于 2012-08-03T20:18:44.597 回答