Home >Backend Development >C++ >How Can C# Structs Efficiently Deserialize Complex JSON Objects from APIs?
Use the C#structure to highly deepen the complicated JSON object
When dealing with complex JSON objects, it is often not enough to only be transformed into a list of basic types. In order to effectively handle the nested structure, the C#structure is recommended.
Question:
JSON object obtained from the Facebook Graph API is unable to be serialized into a list of objects due to invalid original objects.Solution:
Definition structure: Create a separate structure to represent external and internal JSON objects. For example, consider a Friends structure containing a list of FacebookFriend structures:
<code class="language-csharp">public class Friends { public List<FacebookFriend> data { get; set; } } public class FacebookFriend { public string id { get; set; } public string name { get; set; } }</code>
JavaScriptSerializer
Now you can access the internal object by iterating the Data list of the FRIENDS structure: <code class="language-csharp">Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(result);</code>
<code class="language-csharp">foreach (var item in facebookFriends.data) { Console.WriteLine("id: {0}, name: {1}", item.id, item.name); }</code>
The above is the detailed content of How Can C# Structs Efficiently Deserialize Complex JSON Objects from APIs?. For more information, please follow other related articles on the PHP Chinese website!