0

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

1
  • 1
    result.SelectMany(x => x).ToArray() Commented Sep 11, 2020 at 12:25

1 Answer 1

1

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; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for u response .without creating classes is n't possible?.Actually I am adding the response dynamically to the list(List<object> data = new List<object>) and finally returning data.
No not really. Without classes you have to manipulate the json string itself. Which gets messy fast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.