I'm in .NET for WinRT (C#) and I'd like to deserialize a JSON string to a Dictionary<string, object>
, where the dictionary value can later be converted to the actual type.
The JSON string can contain an object hierarchy and I'd like to have child objects in Dictionary<string, object>
as well.
Here's a sample JSON it should be able to handle:
{
"Name":"John Smith",
"Age":42,
"Parent":
{
"Name":"Brian Smith",
"Age":65,
"Parent":
{
"Name":"James Smith",
"Age":87,
}
}
}
I tried with the DataContractJsonSerializer doing as so:
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>), settings);
Dictionary<string, object> results = (Dictionary<string, object>)serializer.ReadObject(ms);
}
This actually works fine for the first level, but then "Parent" is just an object which cannot be casted to a Dictionary<string, object>
:
Dictionary<string, object> parent = (Dictionary<string, object>)results["Parent"];
Cannot cast 'results["Parent"]' (which has an actual type of 'object') to 'System.Collections.Generic.Dictionary<string,object>'
I then tried using Json.NET but child objects are JObject themselves being IDictionary<string, JToken>
, which forces me to iterate through the full hierarchy and convert them over again.
Would someone know how to solve this problem using an existing serializer?
EDIT
I'm using Dictionary<string, object>
because my objects vary from one server call to another (e.g. the "Id" property might be "id", *"cust_id"* or "customerId" depending on the request) and as my app isn't the only app using those services, I can't change that, at least for now.
Therefore, I found it inconvenient to use DataContractAttribute and DataMemberAttribute in this situation.
Instead I'd like to store everything in a generic dictionary, and have a single strongly-typed property "Id" which looks for "id", "cust_id" or "customerId" in the dictionary making it transparent for the UI.
This system works great with JSON.NET, however if ever the server returns an object hierarchy, sub-objects will be stored as JObjects in my dictionary instead of another dictionary.
To sum-up, I'm looking for an efficient system to transform an object hierarchy into a hierarchy of Dictionary<string, object>
using a JSON serializer available in WinRT.
See Question&Answers more detail:
os