Kajbo
Kajbo

Reputation: 1158

Convert object {object[]} to string[]

I have received data of type object {System.Collections.Generic.Dictionary<string, object>}. Parsing this is pretty straightforward:

Dictionary<string, object> parsedData = data as Dictionary<string, object>;

Now I am trying to access parsedData["stringArr"] of type object {object[]}. I got stuck when trying to convert this object {object[]} to string[].

I can't even iterate this:

foreach (object o in parsedData["stringArr"]){}
//returns Exception("...'object' does not contain a public instance definition for GetEnumerator")

Upvotes: 0

Views: 524

Answers (4)

Kajbo
Kajbo

Reputation: 1158

First of all, thank you all for your energy to help me to solve it. I would just bash my keyboard for a few more hours without you. I can't understand why extra conversion to object[] is required yet, but what works is:

Dictionary<string, object> parsedData = data as Dictionary<string, object>;
  if (parsedData.ContainsKey("stringArr"))
            {
                foreach (object o in parsedData["stringArr"] as object[])
                {
                    string myString = o.ToString();
                }

            }

Upvotes: 0

Rufus L
Rufus L

Reputation: 37020

One way you could get the object values as string[] is to use the as cast, just like you did with the original data:

object data = new Dictionary<string, object>
{
    {"stringArr", new[] {"item1", "item2", "item3"}},
};

var parsedData = data as Dictionary<string, object>;

// cast the object values to string[]
foreach (var o in parsedData["stringArr"] as string[])
{
    Console.WriteLine(o);
}

// Output:
// item1
// item2
// item3

Upvotes: 2

Heretic Monkey
Heretic Monkey

Reputation: 12114

If you have a Dictionary<string, object>, and you know a particular key's value has a more specific type, cast it as that type:

foreach (string s in (string[])parsedData["stringArr"])

You will of course receive exceptions if the value at that key is not of that type. A "safer" way of doing it would be to check first:

if (parsedData["stringArr"] as string[] data != null) 
{
    foreach (string s in data) 
    {
        ...
    }
}

Upvotes: 1

Sumner Evans
Sumner Evans

Reputation: 9157

That's because parsedData["stringArr"] is an object, not a object[].

I think you want to change the dictionary type parameters:

Dictionary<string, object[]> parsedData = data as Dictionary<string, object[]>;

Upvotes: 1

Related Questions