2

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; }
    }
3
  • 3
    Just model it as an array - for a single item it will be an array with one item. Commented Aug 3, 2012 at 19:23
  • that's what I was doing originally, but it failed to work. The length of the array was always zero if there was only one item. If I created it as an object, then it would work for single items. Commented Aug 3, 2012 at 19:29
  • I seriously doubt the length of the array was zero if you passed and array with one items. Commented Aug 3, 2012 at 20:12

1 Answer 1

1

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; }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.