Reputation: 41
I have a web API response like below and I need to move all objects into a single array in C# ASP.NET
[
[
{
"id":23,
"name":"John",
"email":"[email protected]",
"appointment_date":"tomorrow",
"appointment_category":3,
"time":"morning"
},
{
"id":35,
"name":"John",
"email":"[email protected]",
"appointment_date":"tomorrow",
"appointment_category":4,
"time":"afternoon"
}
],
[
{
"id":17,
"name":"Alex",
"email":"Alex @domain.com",
"appointment_date":"tomorrow",
"appointment_category":3,
"time":"morning"
}
],
[
{
"id":22,
"name":"Bob",
"email":"[email protected]",
"appointment_date":"tomorrow",
"appointment_category":5,
"time":"morning"
}
]
]
I want to move all objects into single array. Like below
[
{
"id":23,
"name":"John",
"email":"[email protected]",
"appointment_date":"tomorrow",
"appointment_category":3,
"time":"morning"
},
{
"id":17,
"name":"John",
"email":"[email protected]",
"appointment_date":"tomorrow",
"appointment_category":3,
"time":"morning"
},
{
"id":17,
"name":"John",
"email":"[email protected]",
"appointment_date":"tomorrow",
"appointment_category":3,
"time":"morning"
}
]
Please help me Thank u
Upvotes: 0
Views: 131
Reputation: 35524
Not sure if you have deserialized the json already. But you can do it like this. Create 2 classes and deserialize with Newtonsoft.Json. Then use Linq
with SelectMany
to get a list of single object.
//deseralize the json
var list1 = JsonConvert.DeserializeObject<List<List<Class2>>>(json);
//select all the nested items
var list2 = list1.SelectMany(x => x).ToList();
The classes
public class Class1
{
public List<Class1> list { get; set; }
}
public class Class2
{
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
}
Upvotes: 1