Troubleshooting C# JSON Deserialization Errors
Encountering a "primitive object is invalid" error while deserializing a JSON response from the Facebook Graph API (friends list)? This guide provides a solution.
1. Structuring Your C# Classes:
To correctly map the JSON data, define matching C# classes. The structure must mirror the JSON's nested objects and arrays.
public class FacebookFriendsResponse { public List<FacebookFriend> data { get; set; } } public class FacebookFriend { public string id { get; set; } public string name { get; set; } }
2. Deserialization with JavaScriptSerializer
:
Use the JavaScriptSerializer
(available in System.Web.Script.Serialization
) to deserialize the JSON string into your defined class structure.
FacebookFriendsResponse facebookFriends; // ... obtain 'result' string from Facebook API call ... using (var js = new System.Web.Script.Serialization.JavaScriptSerializer()) { facebookFriends = js.Deserialize<FacebookFriendsResponse>(result); }
3. Code Example and Output:
Here's a complete example demonstrating the process:
string json = @"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}"; using (var js = new System.Web.Script.Serialization.JavaScriptSerializer()) { FacebookFriendsResponse facebookFriends = js.Deserialize<FacebookFriendsResponse>(json); foreach (var friend in facebookFriends.data) { Console.WriteLine($"id: {friend.id}, name: {friend.name}"); } }
Output:
<code>id: 518523721, name: ftyft id: 527032438, name: ftyftyf id: 527572047, name: ftgft id: 531141884, name: ftftft</code>
This revised approach ensures accurate mapping of the JSON data, preventing the "primitive object is invalid" error. Remember to handle potential exceptions during the deserialization process. For newer .NET projects, consider using Newtonsoft.Json
for more robust JSON handling.
The above is the detailed content of How to Resolve 'Primitive Object Is Invalid' Error When Deserializing Facebook Graph API JSON in C#?. For more information, please follow other related articles on the PHP Chinese website!