-2

I'm working on a school project. I'm still a newbie at C# and I request JSON from an API that looks like this:

[
    {
        "id": 8402,
        "klant_id": 8401,
        "datum": "2021-03-25",
        "arrangement": "Pitch en Golf 18 holes",
        "personen": 30,
        "pending_online_booking": true,
        "referentie": "8401-1",
        "_links": {
            "curies": [
                {
                    "name": "recras",
                    "href": "/api_docs/{rel}.html",
                    "templated": true
                },
            ],
            "recras:diensten_bij_boeking": {
                "href": "/api2.php/boekingen/8402/diensten"
            },
            "recras:invoices": {
                "href": "/api2.php/boekingen/8402/facturen"
            }
        }
    }
]

I need to put everything in an array so I can work with it. How could I accomplish this?

jps
  • 20,041
  • 15
  • 75
  • 79
  • What do you mean when you say you want to put everything in an array? Do you mean an array of objects, as in the JSON, or do you want to somehow flatten all the values into an array? – ProgrammingLlama Mar 24 '21 at 08:20
  • What you need is to deserialize your json into a list of objects (class type). Create your class with all the json fields and then deserialize as `var values = JsonSerializer.Deserialize<>(jsonString);`. More about json serialization here: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0 – AlleXyS Mar 24 '21 at 08:25

2 Answers2

1

What you need to do is to Deserialize your returned json into into C# objects. You can use an online tool such as https://json2csharp.com/ which will give you something like below to work with in C# and you may alter it as per your need:

public class Cury
{
    public string name { get; set; }
    public string href { get; set; }
    public bool templated { get; set; }
}

public class RecrasDienstenBijBoeking
{
    public string href { get; set; }
}

public class RecrasInvoices
{
    public string href { get; set; }
}

public class Links
{
    public List<Cury> curies { get; set; }

    [JsonProperty("recras:diensten_bij_boeking")]
    public RecrasDienstenBijBoeking RecrasDienstenBijBoeking { get; set; }

    [JsonProperty("recras:invoices")]
    public RecrasInvoices RecrasInvoices { get; set; }
}

public class Root
{
    public int id { get; set; }
    public int klant_id { get; set; }
    public string datum { get; set; }
    public string arrangement { get; set; }
    public int personen { get; set; }
    public bool pending_online_booking { get; set; }
    public string referentie { get; set; }
    public Links _links { get; set; }
}
Alois Bake
  • 11
  • 3
0

ref to:Convert json to a C# array?

you need Newtonsoft.Json(use Nuget in Visual Studio to download this package).

to convert myJsonString to myArray :

object[] myArray = JsonConvert.DeserializeObject<object>(myJsonString);