I have a JSON data like bellow
[{"Staffs":[5,10,12,14]},{"Staffs":[11,13,15,17]}]
and I want to extract value from it and expect bellow data
[5,10,12,14,11,13,15,17]
How can I do this with newtonsoft JSON .
I have a JSON data like bellow
[{"Staffs":[5,10,12,14]},{"Staffs":[11,13,15,17]}]
and I want to extract value from it and expect bellow data
[5,10,12,14,11,13,15,17]
How can I do this with newtonsoft JSON .
You can first parse the JSON to a JArray:
using Newtonsoft.Json.Linq;
var array = JArray.Parse(yourJSONString);
Then, use SelectMany to flatten it and convert it to a List<int>:
var result = array.SelectMany(x => x["Staffs"]).Values<int>().ToList();
first of all create a model
class StaffsModel
{
[JsonProperty("Staffs")]
public int[] Staffs { get; set; }
}
if we consider to created a json value by object like this
var staffsList = new List<StaffsModel>();
staffsList.Add(new StaffsModel { Staffs = new[] { 5, 10, 12, 14 } });
staffsList.Add(new StaffsModel { Staffs = new[] { 11, 13, 15, 17 } });
we can serialize to array with this method
string json = JsonConvert.SerializeObject(staffsList);
with this output [{"Staffs":[5,10,12,14]},{"Staffs":[11,13,15,17]}]
and finally added to list of numbers
var data = JsonConvert.DeserializeObject<StaffsModel[]>(json);
if (data?.Length > 0)
{
var listOfNumbers = new List<int>();
foreach (var staff in data)
{
foreach (var number in staff.Staffs)
{
listOfNumbers.Add(number);
}
}
}