Kokox
Kokox

Reputation: 519

Access multi-dimensional array of multiple types from another class in C#

I am new to C# and have investigated without success. I come from programming in PHP and I have the following JSON:

{"data": [
    {  "iD":0 , "name":"woody", "a":4.0, "b": 3.5, "foo": [5,8] },
    {  "iD":1 , "name":"donald", "a":5.0, "b": 2.4, "foo": [4, 2] }
]}

What I need is to create something similar in C#, if possible in a separate class to be able to access the data in the correct way. I tried to create a different array for each item but I think it is not correct.

From what I've researched, based on the JSON I've presented as an example, I have the following data types: "string, int and double". In PHP you can mix this type of data in the same array and call it through indexes but I don't know exactly how to do the same in C #.

Eye, my question is not how to read the JSON that I have put above, but how to create an similar array (or an object) with that data structure and that I can access it from another class.

I hope I was clear, thanks in advance.

Upvotes: 0

Views: 107

Answers (1)

Sweeper
Sweeper

Reputation: 275125

You should create classes/structs to represent this data's structure:

public class Datum {
    public int ID { get; set; }
    public string Name { get; set; }
    public double A { get; set; }
    public double B { get; set; }
    public List<int> C { get; set; }
}

You can either store this Datum directly in a List<Datum>, or like you have done in the JSON, store it in another class as a property named Data:

public class RootObject {
    public List<Datum> Data { get; set; }
}

Then, you can create these objects using object and collection initialisers:

var rootObject = new RootObject {
    Data = new List<Datum> {
        new Datum {
            ID = 0,
            Name = "Woody",
            A = 4.0,
            B = 3.5,
            C = new List<int> { 5, 8 }
        },
        new Datum {
            ...
        }
    }
}

Upvotes: 2

Related Questions