I have a json blob as below:
{
"name": "ABC",
"type": "School",
"state": {
"events" : [
{
"event": "Session Start",
"timestamp" : 1.6504826230744574E9,
"name": "Session Start 2020",
"venue" : "London"
},
{
"event": "Parents Meet",
"timestamp" : 1.6504826230744574E9,
"name": "Parents Meet 2020",
"venue" : "London",
"noOfAttendees" : 40
},
{
"event": "Annual Fair",
"timestamp" : 1.6504826230744574E9,
"name": "Annual Fair 2020",
"venue" : "London",
"noOfvendors" : 10,
"vendorDetails": {
...
}
},
{
"event": "Session Start",
"timestamp" : 1.6504826881501477E9,
"name": "Session Start 2021",
"venue" : "US"
},
{
"event": "Assembly",
"timestamp" : 1.6504826881501477E9,
"name": "Assembly 2021",
"venue" : "US",
"noOfAttendees" : 50
},
{
"event": "Annual Fair",
"timestamp" : 1.6504826881501477E9,
"name": "Annual Fair 2021",
"venue" : "US",
"noOfvendors" : 20,
"vendorDetails": {
...
}
}
],
"group" : "A"
}
}
This is just an example for the purposes of posting here. In this example, we see that it provides a list of all events that happen for a school every year and the list is a cumulative one i.e. previous year events also get appended. What we know is every year's events will start with 'Session Start' event. I want to go through this object and end with just the latest bunch of events. Please ignore the timestamp or the year in the name of the events, they are just samples here and I don't have that sort of information in real world. The end result I need is :
{
"name": "ABC",
"type": "School",
"state": {
"events" : [
{
"event": "Session Start",
"timestamp" : 1.6504826881501477E9,
"name": "Session Start 2021",
"venue" : "US"
},
{
"event": "Assembly",
"timestamp" : 1.6504826881501477E9,
"name": "Assembly 2021",
"venue" : "US",
"noOfAttendees" : 50
},
{
"event": "Annual Fair",
"timestamp" : 1.6504826881501477E9,
"name": "Annual Fair 2021",
"venue" : "US",
"noOfvendors" : 20,
"vendorDetails": {
...
}
}
],
"group" : "A"
}
}
So, I want to keep the last set of events starting with the 'Session Start' event. I know for sure that there will be >=1 events in this with the name 'Session Start' and I want to keep only the events that follow that very last 'Session Start'.
I can iterate through this using JSONObject and JSONArray, but I'm not sure how to go about editing this object. Please note the name of the events can be different each year eg. due to Covid, we might not have an 'Annual Fair' in year 2022, etc.The only thing static is the 'Session Start' event that i need to grab from the bottom.
CodePudding user response:
you can use jsonArray convert to list,the list data, you defined a Class, this class included event, timestamp... all fields,iterate this list to filter,the last, convert to json
CodePudding user response:
Maybe you need to find all "Session Start" first, then split "name", and sort to get the newest. Edit a JSONArray might not be easy. you can build a new JSONObject with same structure. And only put '2021' event to 'events' list.