I am using the following code to create a paginated list of JSON data for Artist objects:
#RequestMapping(value = "/artists/all", method = RequestMethod.GET, produces = {"application/hal+json"})
public Resources<Artist> getArtists(Pageable pageable) {
final Page<Artist> allArtists= artistService.GetAllArtists(pageable);
for (final Artist artist : allArtists) {
Long artistId = artist.getArtistId();
Link selfLink = linkTo(methodOn(ArtistController.class).getAllArtistById(artistId)).withSelfRel();
artist.add(selfLink);
final Link ordersLink = linkTo(methodOn(MusicController.class).getMusicByArtistId(artistId, pageable)).withRel("musics");
artist.add(ordersLink);
}
Link link =linkTo(ArtistController.class).withSelfRel();
Resources<Artist> result = new Resources<>(allArtists,link);
return result;
}
The code currently returns outputs that are in this format:
{
"artistId": 2,
"name": "Simon Mburu",
"_links": {
"self": {
"href": "http://localhost:8000/api/v1/artists/2"
},
"musics": {
"href": "http://localhost:8000/api/v1/musics/artist/2"
}
}
}
However my intent is to have the code return an output like this:
"pageable": {
"sort": {
"sorted": false,
"unsorted": true
},
"offset": 0,
"pageSize": 20,
"pageNumber": 0,
"paged": true,
"unpaged": false
},
"last": true,
"totalPages": 1,
"totalElements": 2,
"size": 20
"number": 0,
"numberOfElements": 2
"sort": {
// ETC...
What changes can I make to my code to get it to output the data contained in the above example instead of what it currently outputs?
Related
I want to search the key "AylaHeartBeatFrequency" inside nested json. how to search and get its value ? in flutter/dart
{
"sAWSIoT": {
"CloudStatus": 1,
"PairingFlag": 0,
},
"sDebug": {
"LocalDebugMsg_d": "Model ID",
"AylaHeartBeatFrequency": 0
},
"Product": {
"Mode": 1,
"Model": "abc"
},
"data": {
"DeviceType": 300,
"Endpoint": 0,
"UniID": "0000000000000000"
}
}
You can do:
var map = /*put your json here. You can use json.decode() on the json if it's not yet formatted*/, value;
for(var item in map.values) {
if(item.containsKey('AylaHeartBeatFrequency') value = item['AylaHeartBeatFrequency']) ;
}
using ExpressJs/Postgres/Sequelize and when doing findOne I am getting an object return that contains nested objects with following data in the response:
"CompanyVolume": null,
"CompanyMarkets": [],
Is there a way to avoid receiving these properties with null/[] from Postgres?
Appreciate any thoughts...:)
const kyc = await db.Kyc.findOne({
where: {id: req.params.id},
include: [
{model: db.Company,
include: [
{ model: db.CompanyStakeholder, through: db.Role },
{ model: db.CompanyDelivery,
// where: {
// deliveryAverageDurationAmount: {[Op.not]:null},
// }
//returns Cannot read properties of undefined (reading 'not')
},
{ model: db.CompanyVolume },
{ model: db.CompanyDelivery },
{ model: db.CompanyMarket },
],
nest: true,
})
the response object with properties including null or empty arrays
[
{
"id": 5,
"kycTitle": "KYC1006428",
"kycPasscode": null,
"kycDescription": "The best kyc ever, lorem epsum sanctus vita loca",
"kycStartDate": "2022-01-28",
"kycStatus": null,
"kycConsent": "approved",
"kycConsentDate": "2022-01-27T14:01:39.924Z",
"createdAt": "2022-01-27T13:19:41.649Z",
"updatedAt": "2022-01-27T14:01:39.919Z",
"id_User": 1,
"Company": {
"id": 6,
"companyName": "Niky",
"companyEntityType": null,
"companyVatNumber": "",
"companyRegistrationNumber": "",
"companyPubliclyListed": null,
"companyAddress1": "Pepovej 234",
"companyAddress2": "",
"companyCity": "Dada",
"companyPostCode": "3400",
"companyCountry": "Owner",
"companyPhone": "+21321321231",
"createdAt": "2022-01-27T13:19:41.669Z",
"updatedAt": "2022-01-27T13:19:41.676Z",
"KycId": 5,
"CompanyStakeholders": [], //I don't want this returned
"CompanyDelivery": null, //I don't want this returned
"CompanyVolume": null, //I don't want this returned
"CompanyMarkets": [], //I don't want this returned
},
}
]
The different Associations:
Company.associate = function (models) {
Company.hasOne(models.Contact)
Company.hasOne(models.CompanyDelivery)
Company.hasMany(models.CompanyMarket)
Company.hasMany(models.CompanyPosBilling)
Company.hasMany(models.CompanySettlement)
Company.hasOne(models.CompanySubscription)
Company.hasOne(models.CompanyVolume)
Company.hasMany(models.CompanyWebsite)
Company.belongsTo(models.Kyc)
Company.belongsToMany(models.CompanyStakeholder, {
through: models.Role,
unique: false
})
}
CompanyDelivery.associate = function (models) {
CompanyDelivery.belongsTo(models.Company)
}
CompanyMarket.associate = function (models) {
CompanyMarket.belongsTo(models.Company)
}
Kyc.associate = function (models) {
Kyc.hasOne(models.Company)
}
CompanyStakeholder.associate = function (models) {
CompanyStakeholder.belongsToMany(models.Company, {
through: models.Role,
unique: false
})
}
I am making a request to an API which returns me a response.
final response = await http.get(Uri.parse(requestUrl), headers: headers);
It returns the following response.
{
"meta": {
"upcomingMatchCount": 5,
"inProgressMatchCount": 10,
"completedMatchCount": 5
},
"matchList": {
"matches": [
{
"id": 49944,
"matchTypeId": 15,
"series": {
"id": 2739,
"name": "LV= Insurance County Championship 2021",
"shortName": "LV= Insurance County Championship 2021"
},
"name": "",
"status": "LIVE",
"venue": {
"name": "The Cooper Associates County Ground",
"shortName": "The Cooper Associates County Ground"
},
"homeTeam": {
"isBatting": true,
"id": 55,
"name": "Somerset",
"shortName": "SOM"
},
"awayTeam": {
"isBatting": false,
"id": 46,
"name": "Gloucestershire",
"shortName": "GLO"
},
"currentMatchState": "Live",
"isMultiDay": true,
"matchSummaryText": "Live: Gloucestershire won the toss and elected to bowl.",
"scores": {
"homeScore": "8-293",
"homeOvers": "88.0",
"awayScore": "0-0",
"awayOvers": "0"
},
"liveStreams": [],
"isLive": false,
"currentInningId": 1,
"isMatchDrawn": false,
"isMatchAbandoned": false,
"startDateTime": "2021-04-15T10:00:00Z",
"endDateTime": "2021-04-18T17:00:00Z",
"isWomensMatch": false,
"isGamedayEnabled": false,
"removeMatch": false
},
{
"id": 49942,
"matchTypeId": 15,
"series": {
"id": 2739,
"name": "LV= Insurance County Championship 2021",
"shortName": "LV= Insurance County Championship 2021"
},
"name": "",
"status": "LIVE",
"venue": {
"name": "The Spitfire Ground, St Lawrence",
"shortName": "The Spitfire Ground, St Lawrence"
},
"homeTeam": {
"isBatting": false,
"id": 45,
"name": "Kent",
"shortName": "KEN"
},
"awayTeam": {
"isBatting": true,
"id": 40,
"name": "Yorkshire",
"shortName": "YRK"
},
"currentMatchState": "Live",
"isMultiDay": true,
"matchSummaryText": "Live: Yorkshire won the toss and elected to bat.",
"scores": {
"homeScore": "0-0",
"homeOvers": "0",
"awayScore": "8-358",
"awayOvers": "100.0"
},
"liveStreams": [],
"isLive": false,
"currentInningId": 1,
"isMatchDrawn": false,
"isMatchAbandoned": false,
"startDateTime": "2021-04-15T10:00:00Z",
"endDateTime": "2021-04-18T17:00:00Z",
"isWomensMatch": false,
"isGamedayEnabled": false,
"removeMatch": false
},
]
I am retrieving the match list from this response as follows:
final list = map['matchList']['matches'] as List;
I have a Model class which represents each match from the matches key:
class MatchModel {
int id;
int matchTypeId;
Series series;
String name;
String status;
Venue venue;
HomeTeam homeTeam;
HomeTeam awayTeam;
String currentMatchState;
bool isMultiDay;
String matchSummaryText;
Scores scores;
List<Null> liveStreams;
bool isLive;
int currentInningId;
bool isMatchDrawn;
bool isMatchAbandoned;
String startDateTime;
String endDateTime;
bool isWomensMatch;
bool isGamedayEnabled;
bool removeMatch;
MatchModel(
{this.id,
this.matchTypeId,
this.series,
this.name,
this.status,
this.venue,
this.homeTeam,
this.awayTeam,
this.currentMatchState,
this.isMultiDay,
this.matchSummaryText,
this.scores,
this.liveStreams,
this.isLive,
this.currentInningId,
this.isMatchDrawn,
this.isMatchAbandoned,
this.startDateTime,
this.endDateTime,
this.isWomensMatch,
this.isGamedayEnabled,
this.removeMatch});
MatchModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
matchTypeId = json['matchTypeId'];
series =
json['series'] != null ? new Series.fromJson(json['series']) : null;
name = json['name'];
status = json['status'];
venue = json['venue'] != null ? new Venue.fromJson(json['venue']) : null;
homeTeam = json['homeTeam'] != null
? new HomeTeam.fromJson(json['homeTeam'])
: null;
awayTeam = json['awayTeam'] != null
? new HomeTeam.fromJson(json['awayTeam'])
: null;
currentMatchState = json['currentMatchState'];
isMultiDay = json['isMultiDay'];
matchSummaryText = json['matchSummaryText'];
scores =
json['scores'] != null ? new Scores.fromJson(json['scores']) : null;
if (json['liveStreams'] != null) {
liveStreams = new List<Null>();
json['liveStreams'].forEach((v) {
});
}
isLive = json['isLive'];
currentInningId = json['currentInningId'];
isMatchDrawn = json['isMatchDrawn'];
isMatchAbandoned = json['isMatchAbandoned'];
startDateTime = json['startDateTime'];
endDateTime = json['endDateTime'];
isWomensMatch = json['isWomensMatch'];
isGamedayEnabled = json['isGamedayEnabled'];
removeMatch = json['removeMatch'];
}
How do i map data from the list of matches to the list of my MatchModel? Do let me know if you need anything else, any help will be appreciated.
the thing is the response object which is returned is actually a string, so you need to first convert that to json using like
var json = jsonDecode(response).
Once you have it in json format what you can do is access the list as json['matchList']['matches']. So now you can iterater over it like
List<MatchModel> matches = []
for(var match in json['matchList']['matches']){
matches.add(MatchModel.fromJson(match));
}
Hope it's useful.
I would recommend JSON serialization with code generation. In that way you just need a annotation #JsonSerializable for the class, a constructor and part 'match.g.dart'; at the begin of your file. After this, the json_serializable package will generate the Json-converter-methods/factories for you.
For more information you can use this article: https://flutter.dev/docs/development/data-and-backend/json.
Try this.
var json = jsonDecode(response.body)['matchList']['matches'];
List<MatchModel> matches = List.from(json).map((e) => MatchModel.fromJson(Map.from(e))).toList();
Ok, i'm having trouble with getting the relations with typeorm, when i run the service it returns me all the data from the relation, and i want only specific fields, like id and name.
Here's my code:
async findById(id: string): Promise<UsersUseOfferHistoric> {
return await this.repository.findOne({
where: { id },
relations: ['userId', 'offerId'],
});
}
Here's the json Output:
{
"id": "da0fd04e-17c6-4412-b342-a4361d191468",
"createdAt": "2020-01-07T19:48:30.840Z",
"userId": {
"id": "bdc00227-569f-44b5-9bdd-c8de03661ebd",
"name": "Alexandre Vieira",
"cpf": "10443771430",
"email": "av.souza2018#gmail.com",
"password": "asjdsifjdsfasf",
"imagePath": "/me.png",
"active": true,
"lastLogin": "2020-01-07T19:40:26.850Z",
"createdAt": "2020-01-07T19:40:26.850Z",
"updatedAt": "2020-01-07T19:40:26.850Z"
},
"offerId": {
"id": "e399560c-d2c2-4f4e-b2b1-94cae3af3779",
"offerDrescription": "Nova oferta top",
"discountCoupon": " Desconto top",
"discountValidity": "2020-01-07T14:18:19.803Z",
"discountPercentage": 20,
"discountQuantityLimit": 50,
"createdAt": "2020-01-07T19:45:33.589Z",
"updatedAt": "2020-01-07T19:45:33.589Z"
}
}
Here's the output i want:
{
"id": "da0fd04e-17c6-4412-b342-a4361d191468",
"createdAt": "2020-01-07T19:48:30.840Z",
"userId": {
"id": "bdc00227-569f-44b5-9bdd-c8de03661ebd",
"name": "Alexandre Vieira",
},
"offerId": {
"id": "e399560c-d2c2-4f4e-b2b1-94cae3af3779",
"offerDrescription": "Nova oferta top",
}
}
The findOne function accepts an select: ['id', 'createdAt'] property where you can filter the fields of the outgoing relation. To explicitly select the returned fields of a joined table (using the relations property does implicitly a left join) you have to use a query builder.
await getRepository(Foo).createQueryBuilder('foo')
.where({ id: 1})
.select(['foo.id', 'foo.createdAt', 'bar.id', 'bar.name'])
.leftJoin('foo.bars', 'bar') // bar is the joined table
.getMany();
Try something like that:
...findOne({
select: {
id: true,
createdAt: true,
userId: {
id: true,
name: true,
},
offerId: {
id: true,
offerDrescription: true,
},
},
...
where: {...},
})
You can do it like this if you rather use the repository API instead of the queryBuilder
return await this.repository.findOne({
where: { id },
select: {
userId: {
id: true,
name: true
},
offerId: {
id: true,
offerDrescription: true
}
},
relations: {
userId: true,
offerId: true,
}
});
this is my collection
{
"_id": "bRu9ExERzz8PCDwRp",
"persian_title": "عنوان پارسی",
"english_title": "english title",
"price": 5000,
"offer_price": 2000,
"free_for_all": false,
"is_offer": false,
"author_id": "JH3hJGsuYFnRLFLWY"
"Seasons": [
{
"title": "intro",
"free_for_all": false,
"Episodes": [
{
"title": "first episode",
"length": "12",
"url": "0.mp4",
"free_for_all": true
},
{
"title": "second episode",
"length": "05",
"url": "1.mp4",
"free_for_all": false
}
]
}
]
}
i'm trying to get Seasons , episodes where free_for_all is true.
tried this but it doesn't work.
db.courses.find({_id:"bRu9ExERzz8PCDwRp"}, {
"Seasons": {
"$elemMatch": {
"Episodes": {
"$elemMatch": {
"free_for_all": true,
}
}
}
}
})
the result is just like this query :
db.courses.find({_id:"bRu9ExERzz8PCDwRp"})
how can i get only free seasons and episodes?
Your question is ambiguous regarding the desired outcome for free season with non-free episodes, and vice versa, free episodes in non-free seasons. So I'm assuming you want only episodes that are free and are part of a free season. That's what the following will give you (not tested):
_.reduce(db.courses.findOne({_id:"bRu9ExERzz8PCDwRp"}).Seasons, function(all, s) {
if (s.free_for_all) {
all = _.reduce(s.Episodes, function(memo, e) {
if (e.free_for_all) memo.push(e);
return memo;
}, all);
}
return all;
}, []);
If you want all episodes that are free or part of a free season:
_.reduce(db.courses.findOne({_id:"bRu9ExERzz8PCDwRp"}).Seasons, function(all, s) {
if (s.free_for_all) {
all = all.concat(s.Episodes);
} else {
all = _.reduce(s.Episodes, function(memo, e) {
if (e.free_for_all) memo.push(e);
return memo;
}, all);
}
return all;
}, []);