Skip to content

Instantly share code, notes, and snippets.

@zgramana
Created October 2, 2013 20:33
Show Gist options
  • Save zgramana/6800092 to your computer and use it in GitHub Desktop.
Save zgramana/6800092 to your computer and use it in GitHub Desktop.
Quick n dirty function to convert a System.Json.JsonValue to an NSDictionary.
using System.Json;
...
var response = "{ \"foo\": \"bar\" }";
var jsonValue = JsonValue.Parse (response) as JsonObject;
// Split the lambda declaration and initialization
// so that we can do recursion;
Func<JsonValue, NSDictionary> toNSDictionary;
toNSDictionary = (obj)=> {
var keys = new List<NSString> ();
foreach (var k in jsonValue.Keys) {
keys.Add ((NSString)k);
}
var values = new List<NSObject> ();
foreach (var v in jsonValue.Values) {
switch(v.JsonType) {
case JsonType.String:
values.Add ((NSString)(String)v);
break;
case JsonType.Array:
values.Add (NSArray.FromObjects (((JsonArray)v).ToArray()));
break;
case JsonType.Object:
values.Add (toNSDictionary (v));
break;
case JsonType.Number:
case JsonType.Boolean:
values.Add (NSNumber.FromBoolean((JsonPrimitive)v));
break;
default:
throw new ApplicationException(String.Format("Could not convert JsonValue of type {0} to an NSObject.", v.JsonType));
}
}
var dict = NSDictionary.FromObjectsAndKeys (
values.ToArray(),
keys.ToArray()
);
return dict;
};
var nsDict = toNSDictionary(response);
Console.WriteLine (nsDict);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment