Looping through JSON in a C# dictionary - c#

I am trying to implement a PHP function I have already made in C# but I have no idea of the syntax used in C# used to Navigate Dictionaries! (Associative arrays in PHP). What I am doing essentially is making a foreach loop to print each instance of a property in the associative array. I'm not sure if my question is completely clear so to make it easier, What would be the C# equivalent of this?
foreach ( $data->response->docs as $info )
{
echo "{$info->EventId},";
echo "{$info->VenueName},";
}
I just need a nudge in the right direction syntax wise.
Thanks
EDIT-
oops, when I posted this question I was tired. my problem is how to navigate a dictionary serialized from JSON. in my example I was parsing two properties from this sample data :-
{"responseHeader":{"status":0,"QTime":2},"response":{"facet_counts":{},"numFound":110,"docs":[{"VenueSEOLink":"/Aberdeen-Music-Hall-tickets-Aberdeen/venue/443660","VenueId":"10512085.....
etc etc....
So I am trying to figure out how to go down multiple levels through the dict. (C# equivalent of ->)

In C#, you can use a System.Collections.Dictionary or a generic System.Collections.Generic.Dictionary<TKey, TObject>. I recommend the generic dictionary because it is strongly-typed and you don't have to cast the contents every time you retrieve an object.
Assuming your EventId is an int, you can access it like this:
Dictionary<int, string> info = new Dictionary<int, string>();
int eventId = 42;
info[eventId] = "Some value";
var value = info[eventId];
// value = "Some value" as string
If you are using string keys just change the dictionary definition and key type from int to string.
To iterate on a dictionary (or any collection or other object that implements IEnumerable), you use essentially the same syntax as in PHP:
foreach (var item in info) {
// Do something with item
}
More info Systems.Collections.Generic.IDictionary is here.

Related

Dealing with a JSON.Net JArray in Python?

I'm using IronPython as a scripting language in my C# application. One of the "features" that I've implemented is the ability for a script to persist values, which are then exposed to the next script being executed. This is achieved by passing the value(s) to be stored to a C# class, exposed to the script by the "host" application. The code to store a value looks something like this:
store.set("xyz", 123)
('store' is the variable through which the C# object is exposed).
Internally the C# class stores these name/value pairs in a Dictionary<string, object>. When the script finishes executing it serialises the dictionary using Json.Net (var json = JsonConvert.SerializeObject(dict)) and writes the resulting string to file.
When the next script is run, the "host" C# application reads and deserialises the file (JsonConvert.DeserializeObject<Dictionary<string, object>>(s)) and exposes the name/value pairs to the script via the same C# class, which the script can access like this:
my_var = store.get("xyz")
This feature has been working fine with simple types such as ints and floats, but one of our users now needs to persist a list of ints. It works to a fashion - the list gets persisted and exposed to the next Python script, but at this point it is now a JArray type (something to do with Json.Net it seems). This doesn't play nicely with the Python code (which is expecting a list of ints).
I guess the simplest fix is to convert this JArray to a Python int list. But how?
Alternatively it would be nice if the issue could be "fixed" in the C# class (casting?), to avoid users from having to do this conversion in their scripts. However I don't want to change the de/serialisation process to the extent that it no longer reads users' existing data files. Thoughts?
I've found a solution with only minimal impact on script authors. In my C# code, after deserialising the file, I go through the dictionary looking for items with a value of type JArray, and convert them to arrays:
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
var keys = dict.Keys.ToList();
foreach (var key in keys)
{
var jarray = dict[key] as JArray;
if (jarray != null)
{
dict[key] = jarray.ToObject<object[]>();
}
}
These arrays are then exposed to the Python script as before; as they are C# arrays the script authoer must convert to Python lists, which is trivial:
my_var = list(store.get("xyz"))

Dynamic object anonymous type Azure DynamicTableEntity

So I'm doing a exercise with wpf and getting data from azure table but I am using the DynamicTableEnity to query the cloudtableclient. A big issue comes in trying to covert the results that come back to a object that can be displayed in the Datagrid of WPF.
This requires a list of object, which I don't know what object comes back BUT I have all the data in the properites of the DynamicTableEnity. So my first hack at this was as follow.
List<dynamic> dynamicList = new List<dynamic>();
foreach (var entry in tableStorageEntry)
{
var dictionaryObject = AzureConversionHelper.Converstion(entry);
var json = new JavaScriptSerializer().Serialize(dictionaryObject);
dynamic foo = JObject.Parse(json);
dynamicList.Add(foo);
}
public static object Converstion(DynamicTableEntity entity)
{
var dictionary = new Dictionary<string, object>();
dictionary.Add("PartitionKey", entity.PartitionKey);
dictionary.Add("RowKey", entity.RowKey);
dictionary.Add("TimeStamp", entity.Timestamp.ToString());
foreach (var prop in entity.Properties)
{
dictionary.Add(prop.Key, prop.Value.PropertyAsObject);
}
return dictionary;
}
I had no idea what I am doing and it was kind of a struggle since I haven't worked much with anonymous objects. My hack was to convert the properties into a dictionary of strings convert them into a json string and then parse them back into a dynamic object. . . . . that sounds really bad even in my head but after a couple hours of slap around articles of anonymous types I came up with that idea.
This granted how horrible it is works, so its a start for me but it becomes a real issue when I am pull down large set of data, and it makes task almost painful since I'm almost doing a triple read through the data. Can anyone point me to a better method or maybe some pointer on how to better approach this issue.

Construct anonymous object from string, and enumerate through it's properties with reflection

So Basically I have this string which looks like query string "key1=value1&key2=value2" (or maybe JSON I have not decided it yet). so basically I want to convert this string Into an object and then enumerate through its properties (or fields) with reflection. I have already seen something called ExpandoObject but in my case that won't help out, because I cannot enumerate through it's properties, and by that I mean the my properties, like .Key1 and .Key2 (from the string above) with reflection (or may be It is possible and I am doing something wrong). Anyway, any help and suggestion would be appreciated.
EDIT:
the Thing i want to achieve is this. I have an object than I need to store that object in db some have, as a string I gave example above and after that I need to recreate that object again from that string. (just to have the same properties of fields that the object I saved had)
So I have this one method which can be called directly or indirectly. If I call it directly I can create the object which is passed to this method (SomeParamsObject) set it's propertioes and than pass it to the method, If called indirectly I am passing some other object to the other method which is calling that final method. to the first method I am passing some other objects and plus one anonymus object whichs properties are then merged with SomeParamsObject (create inside of the first method by some other objects passed to it) and is passed to the final method. I also need to store this anonymus object somewhere in DB because the call may repeat from the other module of the code, so that's why I need to reconstruct it, To change all this to some KeyValue collection, it would probably take me 4-5 days because this method is really called from bunch of modules of my code.
Can't you use a dictionary, or a NameValueCollection instead ?
var values = new NameValueCollection();
var pairs = "key1=value1&key2=value2".Split('&');
foreach(var kvp in pairs)
{
var parts = kvp.Split('=');
values.Add(parts[0], parts[1]);
}
Then you can access your values with keys:
var value1 = values["key1"];
Use HttpUtility.ParseQueryString method to create a NameValueCollection out of a query string.
var collection = HttpUtility.ParseQueryString("key1=value1&key2=value2");
foreach (string key in collection)
{
string value = collection.Get(key);
//Do whatever with key and value
}

What seems like a basic C# query, but I'm not a C# developer

This won't make a lot of sense so apologies in advance, I'm not a C# developer but have been given some code to look at.
I need to pass a model object in to a function, however I looping through and so will need to build the name dynamically. So lets assume I would normally reference it like so.
model.employee.title
model.employee.forename
How can I reference it using a string for the last part.
I'm using a foreach to loop through the various parts which is fine, but I then need to pass the object in to a function call. I have the name of the last part as a literal string ("title","forname") but I'm not sure how I pass that in.
So effectively what I need is to use something like
model.employee."title"
or
model.employee.varContainingTheName
I know these won't work, but have no idea how to proceed.
Basically, if you have a string of the member name, you're talking about reflection. The reflection API differs between fields and properties, so you'd need to know which it is, for example (where obj is model.employee, and name is the name of the member you want to access):
object value = obj.GetType().GetField(name).GetValue(obj);
vs:
object value = obj.GetType().GetProperty(name).GetValue(obj, null);
Alternatively, use an API like FastMember (which incidentally is much faster than raw reflection - it uses lots of voodoo):
var wrapper = ObjectAccessor.Create(obj);
object value = wrapper[name];
If you develop the model.employee class and use it like that, you should consider using dictionary for fileds.
class employee
{
public Dictionary<string, object> properties = new Dictionary<string,object>();
public employee()
{
properties.Add("time", DateTime.Now);
properties.Add("name", "Bill Gates");
}
}
and then use it like this:
Employee employee = new Employee();
employee.properties["time"];
this code will be faster and easier to read.

Objective-C converting to C#: How can I use a .plist with multiple types in C# if Dictionary is strongly-typed?

The question is a bit complicated so I will try and explain. I have a custom .plist (XML Property List) file I created with Xcode. Within it is many different types of data: NSDictionary, NSArray, NSString, BOOL, etc.
Here's an example:
In my code I can quickly obtain an NSDictionary of this entire file without knowing an data types using the following code (this is ARC code by the way). The only data types that I DO know of is that all of the keys are strings, but the values can be anything I've shown above:
+ (NSDictionary *)configDictionary
{
collectorstemplateAppDelegate *appDelegate = (collectorstemplateAppDelegate*)
[[UIApplication sharedApplication] delegate];
NSString *path = [[NSBundle mainBundle]
pathForResource:appDelegate.currentPlist ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
return dict;
}
What I am trying to do is to accomplish the same thing on C#. I'd like to take these plists and move them to my Windows Phone phone apps, keeping the same structure. I realize that I will need to write some additional code to handle the XML behind the file, but you get the idea.... I want a Dictionary or HashTable or Collection of something similar to what I've done above, without knowing the types of the values.
Obviously in my case something like Dictionary<string, string> isn't going to work for me.
Any help would be great.
Answering my own question here but looking for validation....
Would Dictionary<string, object> work? Because I know the key is a string, I would just need to cast the value to the appropriate type, correct?
int appleID = (int) plistDict["appleid"];
If this is correct or incorrect, someone please let me know.
Hashtable is a non-generic version of Dictionary. In other words it doesn't require you to specify the types it deals with, and you can cash like you would in Objective-C.

Categories

Resources