'How to convert a JSON array to a C# object? [duplicate]

I have a JSON array like this one (the number of elements is not static, there may be also only 2 elements or even 10):

{
    "ids": [1, 2, 3, 4, 5]
}

How can i make it look like this in my C# application:

new object[]{ 1, 2 },

I'm a beginner to C# so I'm sorry if this is a simple question, but I could not find a matching answer. Thank you



Solution 1:[1]

You should define a type to store your data:

public class MyData
{
    [JsonProperty("ids")] // not strictly necessary*
    public int[] Ids { get; set; }
}

Using the JSON.NET NuGet package:

string json = "{\"ids\":[1,2,3,4,5]}";
MyData result = JsonConvert.DeserializeObject<MyData>(json);
int[] ids = result.Ids;

Using the System.Text.Json NuGet package:

string json = "{\"ids\":[1,2,3,4,5]}";
MyData result = JsonSerializer.Deserialize<MyData>(json);
int[] ids = result.Ids;

* The JsonProperty attribute exists in both packages. It's not strictly necessary for your code as they should both handle case sensitivity issues by default, but it's useful to know about for situations where you don't necessarily have the same C# property names as JSON names.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1