0

I have a json with below structure.

{ "root": { "students": [ { "student": { "Id": "1", "Name": "abc" }, "Type": "Update", "Time": "20220520050003Z" }, { "student": { "Id": "2", "Name": "def" }, "Type": "Update", "Time": "20220520050009Z" }, { "student": { "Id": "3", "Name": "ghi" }, "Type": "Create", "Time": "20220520050021Z" }, { "student": { "Id": "1", "Name": "abc" }, "Type": "Create", "Time": "20220520050024Z" } ] } } 

I want to read the students json array and group them which has same Id under student object

For example Id 1 has two entries

{ "student": { "Id": "1", "Name": "abc" }, "Type": "Update", "Time": "20220520050003Z" } 

and

{ "student": { "Id": "1", "Name": "abc" }, "Type": "Create", "eventTime": "20220520050024Z" } 

So I want to group them based on same id and get a list of objects which has record for each unique Id.

I tried with newtonsoft linq , but not able to group them with Id value. I want to know how i can group them

JObject obj = JObject.Parse(jsonasstring); JObject objRoot = (JObject)obj.SelectToken("root"); var studentsList = from students in objRoot["students"] select students["student"]; 
0

2 Answers 2

2

On your example you have different property names("Time", "eventTime") - I assumed that "Time" is a correct one.

Below you can see how grouping was done:

JObject obj = JObject.Parse(jsonasstring); JObject objRoot = (JObject)obj.SelectToken("root"); var studentsList = from students in objRoot["students"] group students by students["student"]["Id"] into studentsgroup select new { StudentId = studentsgroup.Key, Students = studentsgroup.Select(x => new {StudentName = x["student"]["Name"], Type = x["Type"], Time = x["Time"]})}; 

You get students list, group it by studentId and do selection as you need.

Result: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

Select all objects in the students JSON array, then use Linq's GroupBy to bucket them by the student.Id property.

var studentsGroupedById = JObject.Parse(jsonasstring) .SelectTokens("$.root.students[*]") .GroupBy(x => x["student"]["Id"]); 

In each group, Key is the student.Id property, and you can enumerate through all the entries in the group (the inner foreach loop).

Runnable online version that prints out results to demonstrate the groups


I corrected what I hope is a typo in your JSON - the first student entry has a Time property, not an eventTime property. If that's actually how the data is formatted you'll need to account for it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.