I have this
hashtable has a
key "ids" and its values are [1,2,3]
List<long> ids= (List<long>)hashtable["ids"];
an error occurs when trying to cast. It says
Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.List`1[System.Int64]'.
I've been stuck for hours, any suggestions?
It would be helpful if you wrote in your question what are the values you expect to get and the definition of your hashtable.
Assuming You are trying to get [1,2,3] and your 'Value' is an array of long, try:
List<long> ids= hashtable["ids"].ToList();
public static List<dynamic> ToDynamicList(this Hashtable ht)
{
var result = new List<dynamic>();
foreach (DictionaryEntry de in ht)
{
result.Add(new { key = de.Key, value = de.Value });
}
return result;
}
Related
How to get data from array sample code below
var AllData = new Dictionary<string, object>
{
{ "TestFun", await TestFun() },
};
var TestFun = AllData["TestFun"] // ok
ArrayList Humidity = (ArrayList)AllData["TestFun"]; // Error
String String1= TestFun["String1"] // ???
private static async Task<Dictionary<string, object>> TestFun() {
var MultiArray = new Dictionary<string, object>
{
{ "String1", "Value1"},
};
return MultiArray;
}
Error
System.InvalidCastException: 'Unable to cast object of type > 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type > 'System.Collections.ArrayList'.'
Or
Cannot apply indexing with [] to an expression of type 'object'
Tried to get an answer here but couldn't find a solution...
TestFun() returns a Dictionary<string,object>.
System.InvalidCastException: 'Unable to cast object of type > 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type > 'System.Collections.ArrayList'.'
The exception tells you that it is not possible to cast/convert it to an ArrayList. You are trying to go from apples to monkeys.
You can either replace the type of the MultiArray variable to be an ArrayList or change the cast type to Dictionary<string,object>
Dictionary<string, object> TestFun = (Dictionary<string, object>)AllData[key: "TestFun"];
string String1 = (string) TestFun["String1"];
Console.WriteLine(String1); // Value1
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")
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
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[]>;
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)
{
...
}
}
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();
}
}
I have a JObject containing parameter/value pairs (e.g. "param1": "aValue"). I want to update these values from data captured in a data grid.
The parameter values are then validated against a JSON schema that defines the following types: "string", "integer" and "array" (of type "string").
My code works fine for as long as the parameter values are of type string. For integers and arrays I get the following error:
// parameter validation code
..
IList<string> messages;
bool result = Params.IsValid(paramSchema, out messages);
..
// "Validation error: Invalid type. Expected Integer but got String"
// I get a corresponding error for type "Array"
Fair enough, I then added a switch to get the original type so I can cast the new value accordingly:
..
foreach (DataGridViewRow row in Param.Rows)
{
// get current value
JToken curToken = aJObject.GetValue(aDatagrid.row.Cells[0].Value.ToString());
// get new value
JToken newToken = aDatagrid.row.Cells[1].Value.ToString();
switch (currToken.Type)
{
case JTokenType.Integer:
newToken = convertTokenToInt(newToken); // ==> works but custom method
break;
case JTokenType.Array:
newToken = (JTokenType.Array)newToken; // ==> casting does not work!
break;
}
currToken.Replace(newToken);
}
..
With this code I can now handle "strings" and "integers" but I need another custom method for "arrays" (of type "string") or any other type I might use in the future. Not happy with this...
My custom convertTokenToInt(newToken) routine simply assigns the value to an int then reassigns it back to the JToken.
..
int number;
bool result = int.TryParse(aToken.ToString(), out number);
if (result)
{
aToken = number;
return aToken;
}
..
This seems to suggest implicit type conversion is possible with JToken's, so why can't I use casting or ConvertTo() or some other more conventional way to map a datagrid cell value to the appropriate JToken type?
Appreciate any help to resolve this simple problem :-)
... here is my conversion method that works, but maybe there is a more elegant solution ...
private JToken convertTokenToArray(JToken aToken)
{
JArray arr = new JArray();
List<string> items = JsonConvert.DeserializeObject<List<string>>(aToken.ToString());
foreach (var item in items)
{
JToken i = item;
arr.Add(i);
}
return arr;
}
I have an object model that includes an array of longs and I'm deserializing a json string that contains an array using a custom javascript converter and the javascript serializer class.
I thought this would work but it doesn't:
List<long> TheList = new List<long>;
if (dictionary.ContainsKey("TheArray") && dictionary["TheArray"] != null)
{
TheList = serializer.ConvertToType<List<long>>(dictionary["TheArray"]); //bug
TheObject.TheObjectList = (from s in TheList
select Convert.ToInt64(s)).ToList<long>();
}
The error is on the line TheList = serializer.ConvertToType... and the error message is:
Cannot convert object of type 'System.String' to type
'System.Collections.Generic.List`1[System.Int64]'
I also tried this:
var TheStringArray = serializer.ConvertToType<string>(dictionary["TheArray"]);
TheObject.TheObjectList = (from s in TheStringArray.Split(',')
select Convert.ToInt64(s)).ToList<long>();
But then I get this error message:
Type 'System.String' is not supported for deserialization of an array.
What am I missing?
Thanks.
Array is visible to JavaScriptConverter as ArrayList, you may approach the deserialization like this:
List<long> theArray = null;
if (dictionary.ContainsKey("TheArray") && dictionary["TheArray"] is ArrayList)
{
theArray = new List<long>();
ArrayList serializedTheArray = (ArrayList)dictionary["TheArray"];
foreach (object serializedTheArrayItem in serializedTheArray)
{
if (serializedTheArrayItem is Int64)
theArray.Add((long)serializedTheArrayItem);
}
}
This will do all types checking in case there is somethign unexpected in the JSON. Of course it assumes that TheArray property in JSON in fact contains an Array, not inner JSON string which represents Array (the error message might suggest this kind of issue).
I use a 3rd party library and am un able to get the object arrays' content
IDictionary dic=SomeFunc(); // this function returns an IDictionary
and I use DictionaryEntry to get its content
foreach(DictionaryEntry de in dic)
{
//each of de.Value is implemented as a KeyValuePair<object,object>
//I have not yet learned how to read each de.Value's key and value pair
}
Could you offer me a hint to get the strings inside de.Value which is a dictionary of object to object ?
EDIT
Each value of de.Values is a key value pair of type "object" to "object". It reports error when I cast it to string
foreach (DictionaryEntry de in dic)
{
foreach(KeyValuePair<string,string> k in (Dictionary<string,string>)de.Values)
{
//error: instance is null
}
}
make use of is keywork
if(de.value is typeof(Dictionary))
//than do code
not sure but this will work
To access only the values, have this:
foreach (object value in dic.Values)
{
MessageBox.Show(value.ToString());
}
If you mean each value is Dictionary by its own right then you can have nested loop:
foreach (object value in dic.Values)
{
Dictionary<object, object> nestedDic = (Dictionary<object, object>)value;
foreach (object nestedValue in nestedDic.Values)
{
MessageBox.Show(nestedValue.ToString());
}
}