0

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 .

3
  • You first need to translate this json to an array of objects with Staffs property. Then use linq to merge those property values in to a single array. Commented Dec 8, 2019 at 13:42
  • 1
    Use json2csharp.com to create C# classes for your json. Commented Dec 8, 2019 at 13:43
  • Hi @ChetanRanpariya Thanks for reply,can you please give me some code example with newtonsoft json? Commented Dec 8, 2019 at 13:46

2 Answers 2

5

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

2 Comments

Hi @Sweeper thanks for your reply I have another json [{"Manager":6},{"Manager":8}] and I want only value as an array ,like [6,8] and apply your code but not working.can you please help ?
@kuntal If the inner values are not arrays, you'd have to use Select instead.
0

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);
        }
    }
}

Comments

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.