-1

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

  • 3
    FYI: You don't _just_ have an array. You have a JSON object, with a property that is an array of scalar values. – ProgrammingLlama May 02 '22 at 16:12
  • "I have a JSON array" does this mean you have a `JObject` or `JArray` instance, or that you have a string containing the textual representation of the array? – Ben Voigt May 02 '22 at 16:17

1 Answers1

2

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.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • 2
    That is a good approach, but it is not the only one (as the word **need** claims). One can also use Newtonsoft "JSON LINQ" objects such as `JObject` and `JArray` to get to the `int[]` without defining any custom type. – Ben Voigt May 02 '22 at 16:19
  • @BenVoigt True. I've updated to "should". – ProgrammingLlama May 02 '22 at 16:20