确定数组或对象

时间:2012-08-03 19:21:07

标签: c# .net json web-services rest

我已经创建了一个解析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; }
    }

1 个答案:

答案 0 :(得分:1)

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

    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; }