MCR
MCR

Reputation: 1643

Determine if Array or Object

I've created a class to parse a JSON response. The trouble I'm having is that one item is sometimes an array and others an object. I've tried to come up with a workaround, but it always ends up giving me some other problem.

I'd like to have some sort of if or try statement that would let me determine what gets created.

pseudocode...

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

        else{
        [DataMember(Name = "device")]
        public Device devicesObject { get; set; }}
    }

Using Dan's code I came up with the following solution, but now when I try to use it I have a casting issue. "Unable to cast object of type 'System.Object' to type '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; }
    }

Upvotes: 2

Views: 180

Answers (1)

Dan
Dan

Reputation: 9847

Declare the target property as an object. You could then create a helper property that handles whether the target is an array or a single object:

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

Upvotes: 1

Related Questions