JsonArray

SPlatten

New member
Joined
Nov 15, 2024
Messages
1
Programming Experience
10+
I am using C# (Microsoft Visual Studio Professional 2022 (64-bit) Version 4.8.0937, I would like to be able to use JsonArray and JsonObject, when I try to add a reference I type in Json in the search box, the results that area displayed:
Json.NET, 13.0.1.0
Json.NET, 4.5.0.0
System.Text.Json, 8.0.0.3

This doesn't give me access to JsonArray or JsonObject, can anyone please help?
 
As best as I can recall, JsonArray and JsonObject are not types provided by Newtonsoft's Json.NET libraries, regardless of version. I think they would be JArray and JObect respectively if you are using Json.NET.

Anyway, this seems to work just fine with System.Text.Json:
C#:
using System.Text.Json.Nodes;

class Program
{
    static void Main()
    {
        var json = """
            {
                "Star": "Sol",
                "Planets" : [
                    "Mercury",
                    "Venus",
                    "Earth",
                    "Mars",
                    "Jupiter",
                    "Saturn",
                    "Neptune",
                    "Uranus"
                ]
            }
            """;

        var solarSystem = JsonNode.Parse(json);
        JsonObject star = solarSystem.AsObject();
        JsonArray planets = solarSystem["Planets"].AsArray();

        Console.WriteLine(star["Star"]);
        foreach (var planet in planets)
            Console.WriteLine(planet);
    }
}
 
Last edited:
And similar if using .NET Framework 4.8:
C#:
using System;
using System.Text.Json.Nodes;

class Program
{
    static void Main()
    {
        string json = @"{
                ""Star"": ""Sol"",
                ""Planets"" : [
                    ""Mercury"",
                    ""Venus"",
                    ""Earth"",
                    ""Mars"",
                    ""Jupiter"",
                    ""Saturn"",
                    ""Neptune"",
                    ""Uranus""
                ]
            }";

        var solarSystem = JsonNode.Parse(json);
        JsonObject star = solarSystem.AsObject();
        JsonArray planets = solarSystem["Planets"].AsArray();

        Console.WriteLine(star["Star"]);
        foreach (var planet in planets)
            Console.WriteLine(planet);
    }
}
 
Back
Top Bottom