How can I remove some elements of array in Json?

Isabell
Isabell used Ask the Experts™
on
Hi,

My response[0].Body[0].Content has the following value:
{"title":"StudentRecord", "students":[
					{"name":"Josh", "age":"45", "sex":"male}, 
					{"name":"James", "age":"18", "sex":"male}, 
					{"name":"Emily", "age":"25", "sex":"female}, 
					{"name":"Nate", "age":"33", "sex":"male}, 
					{"name":"Nichole", "age":"19", "sex":"female}, 
					{"name":"Janet", "age":"21", "sex":"female}
				      ]
}

Open in new window

What I want to do is remove all the students but the first and last ones from students array so that the result becomes
{"title":"StudentRecord", "students":[
					{"name":"Josh", "age":"45", "sex":"male}, 
					{"name":"Janet", "age":"21", "sex":"female}
				      ]
}

Open in new window


I tried like
var myObj = Newtonsoft.Json.Linq.JObject.Parse(response[0].Bocy[0].Content.ToString());
I know how to remove a property totally, but not partial values from the array.
I am also not sure if I have to convert it to JObject first since then I have to convert it back to the original type of response.

Is there any easier way to solve this issue?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Hi Isabell,

Something like this should do the trick:

dynamic myObj = JsonConvert.DeserializeObject( response[0].Body[0].Content.ToString() );
myObj.students = new JArray( myObj.students.First, myObj.students.Last );

Open in new window

We're deserializing the data, and then we're setting the students property to a new JArray containing just the first and last entry from the existing students property.

To get your JSON formatted data back out, just call ToString() on it:

Console.WriteLine( myObj.ToString() );

Open in new window

Author

Commented:
Thanks Chris!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial