Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

c# - Deserializing a JSON object hierarchy into a hierarchy of Dictionary<string, object>

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm addressing this same issue in a WinRT app using a combination of the JSON.NET library and the ExpandoObject class. The library is able to deserialize JSON data quite nicely into ExpandoObjects, which implement IDictionary. The value of an ExpandoObject's key-value pair may easily be treated as another ExpandoObject.

Here's the approach I used, adapted to your sample:

void LoadJSONData()
{
    string testData = "{ "Name":"John Smith", "Age":42, "Parent": { "Name":"Brian Smith", "Age":65, "Parent": { "Name":"James Smith", "Age":87, } } }";

    ExpandoObject dataObj = JsonConvert.DeserializeObject<ExpandoObject>(testData, new ExpandoObjectConverter());

    // Grab the parent object directly (if it exists) and treat as ExpandoObject
    var parentElement = dataObj.Where(el => el.Key == "Parent").FirstOrDefault();
    if (parentElement.Value != null && parentElement.Value is ExpandoObject)
    {
        ExpandoObject parentObj = (ExpandoObject)parentElement.Value;
        // do something with the parent object...
    }

    // Alternately, iterate through the properties of the expando
    foreach (var property in (IDictionary<String, Object>)dataObj)
    {
        if (property.Key == "Parent" && property.Value != null && property.Value is ExpandoObject)
        {
            foreach (var parentProp in (ExpandoObject)property.Value)
            {
                // do something with the properties in the parent expando
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...