Working with .NET 2 in mono, I'm using a basic JSON
library that returns nested string, object Dictionary and lists.
I'm writing a mapper to map this to a jsonData class that I already have and I need to be able to determine if the underlying type of an object
is a Dictionary or a List. Below is the method I'm using to perform this test, but was wondering if theres a cleaner way?
private static bool IsDictionary(object o) { try { Dictionary<string, object> dict = (Dictionary<string, object>)o; return true; } catch { return false; } } private static bool IsList(object o) { try { List<object> list = (List<object>)o; return true; } catch { return false; } }
The library I'm using is litJson
but the JsonMapper
class essentially doesn't work on iOS, hence the reason I am writing my own mapper.
Since Python 2.2, you should use this code: if isinstance(list2, (str, list, dict)): isinstance() takes a tuple as second argument and returns true if the type is in the tuple.
The simplest approach to check if something is a dictionary in Javascript in a way that will not also return true when given an array is: if (a. constructor == Object) { // code here... }
Equals(Object) Method which is inherited from the Object class is used to check if a specified Dictionary object is equal to another Dictionary object or not. Syntax: public virtual bool Equals (object obj);
Check if Variable is a Dictionary with is Operator We can use the is operator with the result of a type() call with a variable and the dict class. It will output True only if the type() points to the same memory location as the dict class. Otherwise, it will output False .
Use the is
keyword and reflection.
public bool IsList(object o) { if(o == null) return false; return o is IList && o.GetType().IsGenericType && o.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>)); } public bool IsDictionary(object o) { if(o == null) return false; return o is IDictionary && o.GetType().IsGenericType && o.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); }
If you want to check that a certain object is of some type, use the is
operator. For example:
private static bool IsDictionary(object o) { return o is Dictionary<string, object>; }
Though for something this simple, you probably don't need a separate method, just use the is
operator directly where you need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With