How to map JSON Object with Java Pojo Class Spring Boot? - java

How to map JSON object with POJO class in Spring Boot. I have JSON data as below:
{
"report": "Cost History",
"dimensions": [
{
"time": [
{
"label": "Total",
"name": "total"
},
{
"name": "2021-12",
"label": "2021-12",
"direct": null,
"populated": false,
"excluded": null,
"extended": false,
"sort_order": null,
"parent": -1
},
{
"name": "2022-12",
"label": "2022-12",
"direct": null,
"populated": true,
"excluded": null,
"extended": false,
"sort_order": null,
"parent": -1
}
// etc... etc ....
]
},
{
"Azure-Services": [
{
"label": "Total",
"name": "total"
},
{
"name": "3000",
"label": "Storage",
"direct": null,
"populated": null,
"excluded": null,
"extended": false,
"sort_order": null,
"parent": -1
},
{
"name": "3001",
"label": "Storage Account",
"direct": true,
"populated": null,
"excluded": null,
"extended": false,
"sort_order": null,
"parent": 0
}
// .. etc etc
]
}
],
"measures": [
{
"name": "total_cost",
"label": "Total Cost ($)",
"metadata": {
"type": "cost",
"units": "CAD",
"supports_drilldown": true,
"label": "Total Cost ($)"
}
}
],
"interval": "monthly",
"filters": [
"Azure-Services:select:4001,4012"
],
"updated_at": "2022-12-10T06:17:08Z",
"bill_drop_info": [],
"visualization_options": null,
"data": [
[
[
8421.915094617003
],
[
null
],
[
null
],
[
null
]
],
[
[
null
],
[
null
],
[
null
],
[
null
]
],
[
[
null
],
[
null
],
[
null
],
[
null
]
],
[
[
388.6801747227753
],
[
388.6801747227753
],
[
0.5626267227750004
],
[
388.1175480000003
]
],
[
[
872.0477601498656
],
[
872.0477601498656
],
[
1.2152157498662994
],
[
870.8325443999993
]
]
],
"status": "ok",
"enable_dp_popover": false,
"cube_id": "44326_0419_03"
}
and I am getting response from my REST Api like this:
{
"responseMessage": "SUCCESS",
"status": "OK",
"statusCode": 1,
"response": {
"report": "Cost History",
"dimensions": [
{
"time": [
{
"label": "Total",
"name": "total",
"direct": null,
"populated": false,
"excluded": null,
"extended": false,
"sort_order": null,
"parent": 0
},
{
"label": "2021-12",
"name": "2021-12",
"direct": null,
"populated": false,
"excluded": null,
"extended": false,
"sort_order": null,
"parent": -1
},
{
"label": "2022-12",
"name": "2022-12",
"direct": null,
"populated": true,
"excluded": null,
"extended": false,
"sort_order": null,
"parent": -1
}
],
"Azure-Services": []
},
{
"time": [],
"Azure-Services": [
{
"parent": 0,
"label": "Total",
"name": "total",
"direct": false,
"populated": null,
"excluded": null,
"extended": false,
"sort_order": null
},
{
"parent": -1,
"label": "Storage",
"name": "3000",
"direct": false,
"populated": null,
"excluded": null,
"extended": false,
"sort_order": null
},
{
"parent": 0,
"label": "Storage Account",
"name": "3001",
"direct": true,
"populated": null,
"excluded": null,
"extended": false,
"sort_order": null
}
]
}
],
"measures": [
{
"name": "total_cost",
"label": "Total Cost ($)",
"metadata": {
"type": "cost",
"units": "CAD",
"label": "Total Cost ($)",
"supports_drilldown": true
}
}
],
"interval": "monthly",
"filters": [
"Azure-Services:select:4001,4012"
],
"data": [
[
[
8486.168096050156
],
[
8486.168096050156
],
[
9.860766100157399
],
[
8476.30732995
]
],
[
[
null
],
[
null
],
[
null
],
[
null
]
],
[
[
388.6801747227753
],
[
388.6801747227753
],
[
0.5626267227750004
],
[
388.1175480000003
]
],
[
[
872.0477601498656
],
[
872.0477601498656
],
[
1.2152157498662994
],
[
870.8325443999993
],
]
],
"status": "ok",
"updated_at": "2022-12-12T06:38:27Z",
"bill_drop_info": [],
"visualization_options": null,
"enable_dp_popover": false,
"cube_id": "44326_0419_03"
}
}
This is AzureService.java POJO class:
public class AzureService {
#JsonProperty("label")
private String label;
#JsonProperty("name")
private String name;
#JsonProperty("direct")
private boolean direct;
#JsonProperty("populated")
private Object populated;
#JsonProperty("excluded")
private Object excluded;
#JsonProperty("extended")
private boolean extended;
#JsonProperty("sort_order")
private Object sortOrder;
private long parent;
}
This is Time.java POJO class:
public class Time {
#JsonProperty("label")
private String timeLabel;
#JsonProperty("name")
private String timeName;
#JsonProperty("direct")
private Object timeDirect;
#JsonProperty("populated")
private boolean timePopulated;
#JsonProperty("excluded")
private Object timeExcluded;
#JsonProperty("extended")
private boolean timeExtended;
#JsonProperty("sort_order")
private Object timeSortOrder;
#JsonProperty("parent")
private long timeParent;
}
Below is my Dimension.java POJO class:
#Getter
#Setter
public class Dimension {
#JsonProperty("time")
private List<Time> time = new ArrayList<Time>();
#JsonProperty("Azure-Services")
private List<AzureService> azureServices = new ArrayList<AzureService>();
}
This is my CustomReport.java POJO:
#Getter
#Setter
public class CustomReport{
private String report;
private List<Dimension> dimensions = new ArrayList<Dimension>();
private List<Measure> measures = new ArrayList<Measure>();
private String interval;
private List<String> filters = new ArrayList<String>();
#JsonProperty("updated_at")
private String updatedAt;
#JsonProperty("bill_drop_info")
private List<Object> billDropInfo = new ArrayList<Object>();
#JsonProperty("visualization_options")
private Object visualizationOptions;
private List<List<List<Double>>> data = new ArrayList<List<List<Double>>>();
private String status;
#JsonProperty("enable_dp_popover")
private boolean enableDpPopover;
#JsonProperty("cube_id")
private String cubeId;
}
These two classes have properties. I am unable to figure out why these two object showing each others JSON Object response. So is there any JSON property or anything that I need to write before mapping JSON object to POJO?

Related

How to get nested data from a JSON file in Spring Boot?

Here is my json file:
{
"id": "sub_1M3z4ZFuWMT5VbyLdhxe1SGB",
"object": "subscription",
"application": null,
"application_fee_percent": null,
"automatic_tax": {
"enabled": true
},
"billing_cycle_anchor": 1671096923,
"billing_thresholds": null,
"cancel_at": null,
"cancel_at_period_end": false,
"canceled_at": null,
"collection_method": "charge_automatically",
"created": 1668418523,
"currency": "eur",
"current_period_end": 1673775323,
"current_period_start": 1671096923,
"customer": "cus_MnaFTQN0THNHcw",
"days_until_due": null,
"default_payment_method": "pm_1M3z4WFuWMT5VbyLzq2CMtRb",
"default_source": null,
"default_tax_rates": [],
"description": null,
"discount": null,
"ended_at": null,
"items": {
"object": "list",
"data": [
{
"id": "si_MnaFGSZRM6lgJ5",
"object": "subscription_item",
"billing_thresholds": null,
"created": 1668418523,
"metadata": {},
"plan": {
"id": "price_1LN1ZwFuWMT5VbyLdOZ3X83u",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 1900,
"amount_decimal": "1900",
"billing_scheme": "per_unit",
"created": 1658180052,
"currency": "eur",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {},
"nickname": null,
"product": "prod_M5BxCLyY8BJinB",
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"price": {
"id": "price_1LN1ZwFuWMT5VbyLdOZ3X83u",
"object": "price",
"active": true,
"billing_scheme": "per_unit",
"created": 1658180052,
"currency": "eur",
"custom_unit_amount": null,
"livemode": false,
"lookup_key": "mini",
"metadata": {},
"nickname": null,
"product": "prod_M5BxCLyY8BJinB",
"recurring": {
"aggregate_usage": null,
"interval": "month",
"interval_count": 1,
"trial_period_days": null,
"usage_type": "licensed"
},
"tax_behavior": "inclusive",
"tiers_mode": null,
"transform_quantity": null,
"type": "recurring",
"unit_amount": 1900,
"unit_amount_decimal": "1900"
},
"quantity": 1,
"subscription": "sub_1M3z4ZFuWMT5VbyLdhxe1SGB",
"tax_rates": []
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/subscription_items?subscription=sub_1M3z4ZFuWMT5VbyLdhxe1SGB"
},
"latest_invoice": "in_1MFDqoFuWMT5VbyLT3EyrqPd",
"livemode": false,
"metadata": {},
"next_pending_invoice_item_invoice": null,
"on_behalf_of": null,
"pause_collection": null,
"payment_settings": {
"payment_method_options": null,
"payment_method_types": null,
"save_default_payment_method": "off"
},
"pending_invoice_item_interval": null,
"pending_setup_intent": null,
"pending_update": null,
"plan": {
"id": "price_1LN1ZwFuWMT5VbyLdOZ3X83u",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 1900,
"amount_decimal": "1900",
"billing_scheme": "per_unit",
"created": 1658180052,
"currency": "eur",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {},
"nickname": null,
"product": "prod_M5BxCLyY8BJinB",
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"quantity": 1,
-
"trial_end": 1671096923,
"trial_start": 1668418523
}
It's the subscription object from Stripe.
I want to create a class called SubscriptionDetails that has an amount field (in the datas plan object)
I've done that, but with my tests, I see that amount equals 0, I don't know why:
here is my class:
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class SubscriptionDetails implements Serializable {
#JsonProperty("plan")
private Plan plan;
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class Plan {
#JsonProperty("amount")
private int amount;
}
}
Can you help me please ?
I also tried to do this:
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class SubscriptionDetails implements Serializable {
#JsonProperty("plan")
private Plan plan;
}
with Plan object from stripe but it doesn't work.
Here is what i want to test:
#Test
public void testRetrieveSubscriptionDetails_ok()
throws IOException, URISyntaxException, StripeClientException, BadRequestException {
String body = FileUtils.readFileToString(ResourceUtils.getFile("classpath:json/subscriptions-200.json"),
StandardCharsets.UTF_8);
mockServer
.expect(ExpectedCount.once(),
requestTo(new URI("http://localhost:80/v1/subscriptions/sub_1M3z4ZFuWMT5VbyLdhxe1SGB")))
.andExpect(header("Accept", "application/json, application/*+json"))
.andExpect(header("Authorization", "Bearer test")).andExpect(header("Content-Length", "0"))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(body));
SubscriptionDetails subscriptionDetails = this.stripeClient
.retrieveSubscriptionDetails("sub_1M3z4ZFuWMT5VbyLdhxe1SGB");
mockServer.verify();
Assertions.assertThat(subscriptionDetails).isNotNull();
Assertions.assertThat(subscriptionDetails.getTrialEnd()).isEqualTo(1671096923L);
Assertions.assertThat(subscriptionDetails.getAmount()).isEqualTo(19.00);

How to return Response appropriately in Springboot

I am returning Response in my controller using Springboot. I am throwing an Exception in my service class and returning a particular response code when the exception is caught. However, when ever I hit the endpoint on Postman I still gett 200 ok even if an exception was caught.
Here is the service
public Response signup(RegisterDto register) throws CrossPointException{
try{
if (!register.getEmail().matches(EMAIL_PATTERN)){
throw new CrossPointException("Email is invalid");
}
if(!register.getPhoneNumber().matches(PHONE_NUMBER_PATTERN)){
throw new CrossPointException("Phone number is invalid");
}
Optional<User> foundUser = userRepository.findByUsername(register.getEmail());
if(foundUser.isPresent()){
throw new CrossPointException("Email already exist");
}
User user = new User();
user.setFirstName(register.getFirstName());
user.setLastName(register.getLastName());
user.setPhoneNumber(register.getPhoneNumber());
user.setEmail(register.getEmail());
user.setPassword(passwordEncoder.encode(register.getPassword()));
user.setUsername(register.getEmail());
user.setCreatedAt(new Date());
user.setEnabled(false);
user.setRole(Types.Role.BUSINESS);
user.setRcNumber(register.getRcNumber());
user.setUserType(register.getUserType());
user.setRole(Types.Role.INDIVIDUAL);
user.setPartnerName(register.getPartnerName());
user.setBusinessRegistered(register.isBusinessRegistered());
user.setGender(register.getGender());
User savedUser = userRepository.save(user);
basketService.createBasket(savedUser.getId());
GenerateOtpResponseDto response = otpService.generateOtp();
mailService.sendMail(new NotificationEmail("Please Activate your account",
user.getEmail(), "this is your verification cade " + response.getOtp()));
return Response.status(200, "testing this out").entity(BaseResponse.builder().status(true).
responseCode(HttpStatus.OK.toString()).message("Thanks for signing up. Kindly check your " +
"email to activate your account").data(user).build()).build();
}catch (CrossPointException ex){
return Response.status(400, HttpStatus.BAD_REQUEST.toString()).entity(
BaseResponse.builder()
.responseCode(HttpStatus.BAD_REQUEST.toString())
.status(false)
.message(ex.getMessage())
.build()
).build();
}
}
This is what my custom BaseResponse looks like
public class BaseResponse<T> {
private boolean status;
private String message;
private String responseCode;
#JsonInclude(JsonInclude.Include.NON_NULL)
private T data;
}
When I hit the endpoint I am getting a number of things that are needless as part of the response.
{
"context": {
"headers": {},
"configuration": null,
"entity": {
"context": {
"headers": {},
"configuration": null,
"entity": {
"status": false,
"message": "Email already exist",
"responseCode": "400 BAD_REQUEST"
},
"entityType": "com.crosspoint.crosspointfinance.data.model.BaseResponse",
"entityAnnotations": [],
"entityStream": {
"committed": false,
"closed": false
},
"length": -1,
"language": null,
"location": null,
"mediaType": null,
"committed": false,
"date": null,
"lastModified": null,
"allowedMethods": [],
"acceptableMediaTypes": [
{
"type": "*",
"subtype": "*",
"parameters": {},
"quality": 1000,
"wildcardType": true,
"wildcardSubtype": true
}
],
"links": [],
"entityTag": null,
"stringHeaders": {},
"entityClass": "com.crosspoint.crosspointfinance.data.model.BaseResponse",
"responseCookies": {},
"acceptableLanguages": [
"*"
],
"requestCookies": {},
"lengthLong": -1
},
"status": 400,
"length": -1,
"language": null,
"location": null,
"mediaType": null,
"cookies": {},
"metadata": {},
"date": null,
"lastModified": null,
"allowedMethods": [],
"entity": {
"status": false,
"message": "Email already exist",
"responseCode": "400 BAD_REQUEST"
},
"statusInfo": {
"reasonPhrase": "400 BAD_REQUEST",
"statusCode": 400,
"family": "CLIENT_ERROR"
},
"links": [],
"entityTag": null,
"stringHeaders": {},
"headers": {}
},
"entityType": "org.glassfish.jersey.message.internal.OutboundJaxrsResponse",
"entityAnnotations": [],
"entityStream": {
"committed": false,
"closed": false
},
"length": -1,
"language": null,
"location": null,
"mediaType": null,
"committed": false,
"date": null,
"lastModified": null,
"allowedMethods": [],
"acceptableMediaTypes": [
{
"type": "*",
"subtype": "*",
"parameters": {},
"quality": 1000,
"wildcardType": true,
"wildcardSubtype": true
}
],
"links": [],
"entityTag": null,
"stringHeaders": {},
"entityClass": "org.glassfish.jersey.message.internal.OutboundJaxrsResponse",
"responseCookies": {},
"acceptableLanguages": [
"*"
],
"requestCookies": {},
"lengthLong": -1
},
"status": 200,
"length": -1,
"language": null,
"location": null,
"mediaType": null,
"cookies": {},
"metadata": {},
"date": null,
"lastModified": null,
"allowedMethods": [],
"entity": {
"context": {
"headers": {},
"configuration": null,
"entity": {
"status": false,
"message": "Email already exist",
"responseCode": "400 BAD_REQUEST"
},
"entityType": "com.crosspoint.crosspointfinance.data.model.BaseResponse",
"entityAnnotations": [],
"entityStream": {
"committed": false,
"closed": false
},
"length": -1,
"language": null,
"location": null,
"mediaType": null,
"committed": false,
"date": null,
"lastModified": null,
"allowedMethods": [],
"acceptableMediaTypes": [
{
"type": "*",
"subtype": "*",
"parameters": {},
"quality": 1000,
"wildcardType": true,
"wildcardSubtype": true
}
],
"links": [],
"entityTag": null,
"stringHeaders": {},
"entityClass": "com.crosspoint.crosspointfinance.data.model.BaseResponse",
"responseCookies": {},
"acceptableLanguages": [
"*"
],
"requestCookies": {},
"lengthLong": -1
},
"status": 400,
"length": -1,
"language": null,
"location": null,
"mediaType": null,
"cookies": {},
"metadata": {},
"date": null,
"lastModified": null,
"allowedMethods": [],
"entity": {
"status": false,
"message": "Email already exist",
"responseCode": "400 BAD_REQUEST"
},
"statusInfo": {
"reasonPhrase": "400 BAD_REQUEST",
"statusCode": 400,
"family": "CLIENT_ERROR"
},
"links": [],
"entityTag": null,
"stringHeaders": {},
"headers": {}
},
"statusInfo": "OK",
"links": [],
"entityTag": null,
"stringHeaders": {},
"headers": {}
}
This is response is too lengthy and contains a lot of useless info.
All I want is something like this:
{
"status": true,
"message": "Successfully Joined wait-list",
"responseCode": "200 OK",
"data": {
"id": "6349a3be93a8523e3f40ee00",
"email": "ojoi#gmail.com",
"firstName": "Ojo"
}
}
This is what my controller looks like
#PostMapping("/signup")
#PermitAll
public Response signUp(#RequestBody RegisterDto register) throws CrossPointException{
return Response.ok(auth.signup(register)).build();
}

doOnEach rather that flatMap/concatMap

Introduction
I am currently working on a project to achieve a bulk insertion in a Couchbase database.
For this, I chose Quarkus Reactive to get data from the client. And I used a Flux to insert all the data to database.
For each data inserted, I send a response, example of a response:
[
{
"data": {
"id": "1"
"created": "2022-02-22T00:28:34Z",
"lastName": "DUPOND",
"firstName": "Marianne",
"gender": "FEMALE",
"title": "MRS",
"addresses": [
{
"street1": "rue du Testeur",
"zipCode": "34000",
"city": "MONTPELLIER",
"country": "France",
"typeKey": "PERSONAL"
}
],
"phones": [
{
"number": "0610529856",
"typeKey": "PERSONAL"
}
],
"emails": [
{
"email": "marianne.dupond#test.com",
"typeKey": "PERSONAL"
}
],
"birthday": "1987-11-13",
"languages": [
"FR",
"EN"
],
"socialNetworks": [
{
"socialNetworkId": "marianne.dupond#twitter",
"typeKey": "PERSONAL"
}
],
"customFields": [
{
"customFieldKey": "MAIDEN_NAME",
"value": "DURAND"
}
]
},
"result": "201",
"id":"1"
},
{
"data": {
"id" : "2"
"created": "2022-02-22T00:28:34Z",
"lastName": "BOND",
"firstName": "James",
"gender": "MALE",
"title": "MR",
"addresses": [
{
"street1": "boulevard des services secrets",
"zipCode": "10000",
"city": "LONDRES",
"country": "Royaume-Uni",
"typeKey": "PERSONAL"
}
],
"phones": [
{
"number": "0600700700",
"typeKey": "PERSONAL"
}
],
"emails": [
{
"email": "james.bond#test.com",
"typeKey": "PERSONAL"
}
],
"birthday": "1950-07-07",
"languages": [
"EN"
],
"socialNetworks": [
{
"socialNetworkId": "james.bond#facebook",
"typeKey": "PERSONAL"
}
],
"customFields": [
{
"customFieldKey": "VIP",
"value": "1"
}
]
},
"result": "201",
"id": "2"
}
]
Problematic
But currently the returned response is:
[
{
"data": {
"id": "1"
"created": "2022-02-22T00:37:39Z",
"lastName": "DUPOND",
"firstName": "Marianne",
"gender": "FEMALE",
"title": "MRS",
"addresses": [
{
"street1": "rue du Testeur",
"zipCode": "34000",
"city": "MONTPELLIER",
"country": "France",
"typeKey": "PERSONAL"
}
],
"phones": [
{
"number": "0610529856",
"typeKey": "PERSONAL"
}
],
"emails": [
{
"email": "marianne.dupond#test.com",
"typeKey": "PERSONAL"
}
],
"birthday": "1987-11-13",
"languages": [
"FR",
"EN"
],
"socialNetworks": [
{
"socialNetworkId": "marianne.dupond#twitter",
"typeKey": "PERSONAL"
}
],
"customFields": [
{
"customFieldKey": "MAIDEN_NAME",
"value": "DURAND"
}
]
},
"result": "201"
},
{
"data": {
"created": "2022-02-22T00:37:39Z",
"lastName": "BOND",
"firstName": "James",
"gender": "MALE",
"title": "MR",
"addresses": [
{
"street1": "boulevard des services secrets",
"zipCode": "10000",
"city": "LONDRES",
"country": "Royaume-Uni",
"typeKey": "PERSONAL"
}
],
"phones": [
{
"number": "0600700700",
"typeKey": "PERSONAL"
}
],
"emails": [
{
"email": "james.bond#test.com",
"typeKey": "PERSONAL"
}
],
"birthday": "1950-07-07",
"languages": [
"EN"
],
"socialNetworks": [
{
"socialNetworkId": "james.bond#facebook",
"typeKey": "PERSONAL"
}
],
"customFields": [
{
"customFieldKey": "VIP",
"value": "1"
}
]
},
"result": "201"
}
]
The id field inside the data and the response field do not appear, and sometimes the id field inside the data of the first element appears, sometimes not.
Affected code
Bulk insertion(flux of single insertion) code:
public Flux<SingleResponseBulk> bulkInsertCustomerProfile(Multi<SingleResponseBulk> singleResponses) {
return Flux.from(singleResponses)
.doOnEach(signal -> {
if (signal.hasValue()) {
SingleResponseBulk singleResponseBulk = Objects.requireNonNull(signal.get());
insertCustomerProfileWithSingleResponseBulk(singleResponseBulk);
}
});
}
private void insertCustomerProfileWithSingleResponseBulk(SingleResponseBulk response) {
try {
insertCustomerProfile(response.getData()).subscribe();
response.setId(response.getData().getId());
response.setResult("201");
} catch (CouchbaseException e) {
response.setResult("400");
response.setError(e.getMessage());
}
}
Single insertion code:
public Mono<CustomerProfile> insertCustomerProfile(CustomerProfile customerProfile) {
customerProfile.setCreated(LocalDateTime.now());
return getNextId().flatMap(counterResult -> {
String id = String.valueOf(counterResult.content());
customerProfile.setId(id);
String key = getDocumentKey(id);
return collection.insert(key, customerProfile)
.flatMap(result -> {
customerProfile.setCas(result.cas());
return Mono.just(customerProfile);
})
.doOnError(CouchbaseException.class, mapCouchbaseExceptionConsumer(id));
});
}
Id generation code:
private Mono<CounterResult> getNextId() {
return collection.binary()
.increment("counter" + COLLECTION_DELIMITER + CUSTOMER_PROFILE_COLLECTION)
.doOnError(CouchbaseException.class, error -> {
String errorMessage = "An exception occurred during id generation.";
throw new RepositoryException(errorMessage, error);
});
}
Question
So I was wondering if it would be possible to solve the problem. If so, how can we do it?

how to sort and limit embeded arrays using spring data mongorepository

I am trying to sort and limit embeded arrays using pagination, is that possible to acheive this using MongoRepository. Below is my json, and i am trying to get top ten notifications
{
"id":"5d357ce265cb136751177aas",
"notifications": [
{
"id": "5d357ce743cb133241177aaa",
"owner": null,
"itemId": "5d357ce743cb11254584abg",
"type": null,
"createdOn": "2019-07-22T03:41:05.428+00:00",
"read": false
},
{
"id": "5d357d2b43cb133241177aaf",
"owner": null,
"itemId": "5d35745243cb11256954abg",
"type": null,
"createdOn": "2019-07-22T03:41:14.367+00:00",
"read": false
}
]
}
i expect the output like this
"notifications": [
{
"id": "5d357d2b43cb133241177aaf",
"owner": null,
"itemId": "5d35745243cb11256954abg",
"type": null,
"createdOn": "2019-07-22T03:41:14.367+00:00",
"read": false
},
{
"id": "5d357ce743cb133241177aaa",
"owner": null,
"itemId": "5d357ce743cb11254584abg",
"type": null,
"createdOn": "2019-07-22T03:41:05.428+00:00",
"read": false
}
]
This may help:
db.collection.update( { <query selector> }, { <update operator>: {
"array.$.field" : value } } )

Generalised solution to edit a json for SCIM apis using the attributes and excludedAttributes

Below is the original response:
{
"emails": [
{
"type": "work",
"value": "bjensen#example.com"
}
],
"id": "2819c223-7f76-453a-919d-413861904646",
"phoneNumbers": [
{
"type": "work",
"value": "555-555-8377"
},
{
"type": "business",
"value": "555-555-8377"
}
],
"schemas": [
"urn:scim:schemas:core:1.0"
],
"userName": "bjensen"
}
And in the above response I would pass excludedAttributes=phoneNumbers.type and the response should be like below:
{
"emails": [
{
"type": "work",
"value": "bjensen#example.com"
}
],
"id": "2819c223-7f76-453a-919d-413861904646",
"phoneNumbers": [
{
"value": "555-555-8377"
},
{
"value": "555-555-8377"
}
],
"schemas": [
"urn:scim:schemas:core:1.0"
],
"userName": "bjensen"
}

Categories

Resources