Home >Backend Development >C++ >How to Successfully Deserialize JSON Objects Containing Lists in C#?

How to Successfully Deserialize JSON Objects Containing Lists in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-02-02 07:06:08419browse

How to Successfully Deserialize JSON Objects Containing Lists in C#?

Use C# counter -sequence json

When trying to sequence the JSON object into a list of objects, it may be difficult due to the invalid original object. This article will provide a solution to this problem, so that you can successfully lead to such JSON objects.

Consider the following JSON objects, it indicates that the Facebook friends list obtained through Graph API:

To discern this JSON object, we need to create a structure that matches its mode. In this example, it is a FacebookFriend object list:
<code>{
    "data": [
        {
            "id": "518523721",
            "name": "ftyft"
        },
        // 更多数据...
    ]
}</code>

After defining these structures, we can now use JavaScriptSerializer to serialize JSON objects:
<code class="language-csharp">public class FriendData
{
    public List<FacebookFriend> data { get; set; }
}

public class FacebookFriend
{
    public string id { get; set; }
    public string name { get; set; }
}</code>

This will create a FriendData object containing a list of Facebookfriend objects, which can access each friend data. Please note that the names used here are only used to explain the purpose; choose the appropriate category name for your project.
<code class="language-csharp">FriendData facebookFriends = new JavaScriptSerializer().Deserialize<FriendData>(result);</code>

In order to demonstrate the process of the deepening sequence, please consider the following test code:

executing this code will generate the following output:
<code class="language-csharp">string json =
    @"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";

FriendData facebookFriends = new JavaScriptSerializer().Deserialize<FriendData>(json);

foreach (var item in facebookFriends.data)
{
    Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
}</code>

This demonstrates the process of successfully serializing the JSON object into a list of FacebookFriend objects.
<code>id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft</code>

The above is the detailed content of How to Successfully Deserialize JSON Objects Containing Lists in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn