How to turn a String into ArrayList<Details>? - java

The browser sends the following object to the backend:
Now I would like to store the data in my database. So I have an entity that looks like this:
#Entity
public class NewQuote {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String description;
#ElementCollection(targetClass = Details.class)
private List<Details> details = new ArrayList<>();
public NewQuote(String description, ArrayList<Details> details) {
this.description = description;
this.details = details;
}
#Embeddable
public class Details {
private String description;
private String label;
public Details(String description, String label) {
this.description = description;
this.label = label;
}
public Details() {}
}
Controller
#PostMapping(value = "/save-quote", produces = MediaType.APPLICATION_JSON_VALUE)
public void saveQuote(#RequestBody Map<String, String> data) {
newQuoteService.saveQuote(data);
}
Service
public void saveQuote(Map<String, String> data) {
JSONObject json = new JSONObject(data);
NewQuote newQuote = new NewQuote(
json.getAsString("description"),
json.getAsString("details")
);
newQuoteRepository.save(newQuote);
}
I am getting an error because json.getAsString("details") should not be a string of course. So how can I turn it to ArrayList<Details>?

Add a DTO to manage your json response. You don't need to explicitly use JSONObject because spring already manage the process of mapping under the wood with Jackson.
Also, it is not a good practice to pass your Entities directly into the controller methods.
NewQuoteDto.java
public class NewQuoteDto {
private Long id;
private String description;
private List<Details> details = new ArrayList<>();
public NewQuoteDto() {
}
// getter and setter or you can use lombok
}
DetailDto.java
public class DetailDto {
private String description;
private String label;
public DetailDto() {}
// getter and setter or you can use lombok
}
Controller
#PostMapping(value = "/save-quote", produces = MediaType.APPLICATION_JSON_VALUE)
public void saveQuote(#RequestBody NewQuoteDto dataDto) {
// here you map dataDto to your model before you call saveQuote
NewQuote data = mapper.map(dataDto, NewQuote.class); // if you use ModelMapper library.
newQuoteService.saveQuote(data);
}
For custom mapping take look here.

Related

How to flatten nested json to map with entity using Java 8 Stream?

I have a structure that looks like this for RechargeResponse Model:
public class RechargeResponse {
private String code;
private String status;
private Set<OperatorWiseCircles> payload;
// setter and getters
}
here is the OperatorWiseCircles Model
public class OperatorWiseCircles {
private String operatorName;
private String operatorId;
private List<CircleWisePlan> circleWisePlanLists;
//setter and getters
}
CircleWisePlan Model class
public class CircleWisePlan {
private String circleName;
private String circleId;
}
Below is the sample json which we need to flattern.
{
"code": 200,
"status": "SUCCESS",
"payload": [
{
"operatorName": "VODAFONE",
"operatorId": "VF",
"circleWisePlanLists": [
{
"circleName": "C1",
"circleId": "1"
},
{
"circleName": "C2",
"circleId": "2"
}
]
}
]
}
I am expecting this to be flattern and map it to Entity object, so that I can add all these iteration to Hashset and save them all to DB, I want to do it using java8 stream. I how can I do it efficiently. I didnt get the right example, to parse nested json values and create entities for it using map/ flatmap.
Result should be like
Eg: ["VODAFONE","VF","C1", "1"]--->
ENTRY1
["VODAFONE","VF","C2", "2"] ---> ENTRY2
#Entity
public class RechargePlanEntity extends Audit<String>{
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name="operator_name")
private String operatorName;
#Column(name="operator_id")
private String operatorId;
#Column(name="circle_name")
private String circleName;
#Column(name="circle_id")
private String circleId;
}
Truth is I'm sure is there any easy way to do this, Yet you can follow something like this,
Here in this example I have created utility class to map OperatorWiseCircles class to List<RechargePlanEntity>.
public class Main {
public static void main(String[] args) throws IOException {
String s = "{\"code\":200,\"status\":\"SUCCESS\",\"payload\":[{\"operatorName\":\"VODAFONE\",\"operatorId\":\"VF\",\"circleWisePlanLists\":[{\"circleName\":\"C1\",\"circleId\":\"1\"},{\"circleName\":\"C2\",\"circleId\":\"2\"}]}]}";
ObjectMapper om = new ObjectMapper();
RechargeResponse response = om.readValue(s, RechargeResponse.class);
List<RechargePlanEntity> collection = response.getPayload()
.stream()
.map(MapUtil::toEntity)
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println(collection);
}
}
#Getter
#Setter
#ToString
class RechargePlanEntity {
private Long id;
private String operatorName;
private String operatorId;
private String circleName;
private String circleId;
}
#Getter
#Setter
class RechargeResponse {
private String code;
private String status;
private Set<OperatorWiseCircles> payload;
}
#Getter
#Setter
class OperatorWiseCircles {
private String operatorName;
private String operatorId;
private List<CircleWisePlan> circleWisePlanLists;
}
#Getter
#Setter
class CircleWisePlan {
private String circleName;
private String circleId;
}
final class MapUtil {
public static List<RechargePlanEntity> toEntity(OperatorWiseCircles in) {
return in.getCircleWisePlanLists()
.stream()
.map(MapUtil::map)
.peek(out -> map(in, out))
.collect(Collectors.toList());
}
private static RechargePlanEntity map(CircleWisePlan in) {
RechargePlanEntity out = new RechargePlanEntity();
out.setCircleId(in.getCircleId());
out.setCircleName(in.getCircleName());
return out;
}
private static void map(OperatorWiseCircles in, RechargePlanEntity out) {
out.setOperatorId(in.getOperatorId());
out.setOperatorName(in.getOperatorName());
}
}
The entities without ids may be created from RechargeResponse model providing that the entity has all-args constructor:
RechargeResponse modelFromJson = ... //
List<RechargePlanEntity> entities = modelFromJson.getPayload()
.stream() // Stream<OperatorWiseCircles>
.flatMap(ows -> ows.getCircleWisePlanLists()
.stream() // Stream<CircleWisePlan>
.map(cwp -> new RechargePlanEntity(
null, // instead of id
ows.getOperatorName(),
ows.getOperatorId(),
cwp.getCircleName(),
cwp.getCircleId()
)) // Stream<RechargePlanEntity>
) // Stream<RechargePlanEntity>
.collect(Collectors.toList());
or, if a builder is implemented in the entity class (e.g. using Lombok's #Builder annotation), this conversion may look as follows:
List<RechargePlanEntity> entities = modelFromJson.getPayload()
.stream() // Stream<OperatorWiseCircles>
.flatMap(ows -> ows.getCircleWisePlanLists()
.stream() // Stream<CircleWisePlan>
.map(cwp -> RechargePlanEntity.builder()
.operatorName(ows.getOperatorName())
.operatorId(ows.getOperatorId())
.circleName(cwp.getCircleName())
.circleId(cwp.getCircleId())
.build()
) // Stream<RechargePlanEntity>
) // Stream<RechargePlanEntity>
.collect(Collectors.toList());

How work with immutable object in mongodb and lombook without #BsonDiscriminator

I tried to work with immutable objects in MongoDB and Lombok. I found a solution to my problem but it needs to write additional code from docs but I need to used Bson annotations and create a constructor where describes fields via annotations. But if I user #AllArgsConstructor catch exception: "Cannot find a public constructor for 'User'" because I can't use default constructor with final fields. I think i can customize CodecRegistry correctly and the example will work correctly but I couldn't find solution for it in docs and google and Stackoverflow.
Is there a way to solve this problem?
#Data
#Builder(builderClassName = "Builder")
#Value
#BsonDiscriminator
public class User {
private final ObjectId id;
private final String name;
private final String pass;
private final String login;
private final Role role;
#BsonCreator
public User(#BsonProperty("id") final ObjectId id,
#BsonProperty("name") final String name,
#BsonProperty("pass") final String pass,
#BsonProperty("login") final String login,
#BsonProperty("role") final Role role) {
this.id = id;
this.name = name;
this.pass = pass;
this.login = login;
this.role = role;
}
#AllArgsConstructor
public enum Role {
USER("USER"),
ADMIN("ADMIN"),
GUEST("GUEST");
#Getter
private String value;
}
public static class Builder {
}
}
Example for MongoDB where I create, save and then update users:
public class ExampleMongoDB {
public static void main(String[] args) {
final MongoClient mongoClient = MongoClients.create();
final MongoDatabase database = mongoClient.getDatabase("db");
database.drop();
final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
final MongoCollection<User> users = database.getCollection("users", User.class).withCodecRegistry(pojoCodecRegistry);
users.insertMany(new ExampleMongoDB().getRandomUsers());
System.out.println("Before updating:");
users.find(new Document("role", "ADMIN")).iterator().forEachRemaining(
System.out::println
);
System.out.println("After updating:");
users.updateMany(eq("role", "ADMIN"), set("role", "GUEST"));
users.find(new Document("role", "GUEST")).iterator().forEachRemaining(
System.out::println
);
}
public List<User> getRandomUsers() {
final ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 15; i++) {
users.add(
User.builder()
.login("log" + i)
.name("name" + i)
.pass("pass" + i)
.role(
(i % 2 == 0) ? User.Role.ADMIN : User.Role.USER
).build()
);
}
return users;
}
}
This should work (it worked for me):
#Builder(builderClassName = "Builder")
#Value
#AllArgsConstructor(onConstructor = #__(#BsonCreator))
#BsonDiscriminator
public class User {
#BsonId
private final ObjectId _id;
#BsonProperty("name")
private final String name;
#BsonProperty("pass")
private final String pass;
#BsonProperty("login")
private final String login;
#BsonProperty("role")
private final Role role;
}
Then in lombok.config add these (in your module/project directory):
lombok.addLombokGeneratedAnnotation=true
lombok.anyConstructor.addConstructorProperties=true
lombok.copyableAnnotations += org.bson.codecs.pojo.annotations.BsonProperty
lombok.copyableAnnotations += org.bson.codecs.pojo.annotations.BsonId
Also piece of advice, keep _id if you are going to use automatic conversion to POJOs using PojoCodec, which will save a lot of trouble.

How to collect all xml elements in a list?

I am using jackson-dataformat-xml.
I have the following classes:
public class CTHotel {
#JacksonXmlProperty(localName = "basic-info")
private HotelBaseInfo hotelBaseInfo;
//other properties and getters and setters
}
public class HotelBaseInfo {
#JacksonXmlProperty(localName = "hotel-name")
private String hotelName;
#JacksonXmlElementWrapper(localName = "hotel-amenities")
private List<HotelAmenity> hotelAmenities;
//other properties and getters/setters
}
public class HotelAmenity {
private String category;
private String description;
#JacksonXmlElementWrapper(localName = "amenities")
private List<String> amenities;
//other properties and getters/setters
}
My XML is this:
<hotels>
<hotel>
<basic-info>
<hotel-name>Hotel XYZ</hotel-name>
<hotel-amenities>
<hotel-amenity>
<category>F&B</category>
<description>Random Text</description>
<amenities>
<amenity>Cafe</amenity>
<amenity>Bar</amenity>
<amenity>Rastaurant</amenity>
</amenities>
</hotel-amenity>
<hotel-amenity>
...
</hotel-amenity>
</hotel-amenities>
</basic-info>
</hotel>
<hotel>
...
</hotel>
</hotels>
My question is, how can I map amenities as list of strings in my HotelAmenity class as mentioned above ? What annotation should I use on amenities field ?
#JacksonXmlElementWrapper annotation on hotelAmenities field of Hotel class is working just fine.
I get the below error while mapping :
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
at [Source: java.io.StringReader#507bcc81; line: 3, column: 1039] (through reference chain: com.example.response.HotelSearchResponse["hotels"]->java.util.ArrayList[2]->com.example.response.CTHotel["basic-info"]->com.example.response.HotelBaseInfo["hotel-amenities"]->java.util.ArrayList[1]->com.example.response.HotelAmenity["amenities"]->java.util.ArrayList[9])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) ~[jackson-databind-2.6.5.jar:2.6.5]
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:857) ~[jackson-databind-2.6.5.jar:2.6.5]
...
Here's the code, that I hope would answer your question:
/**Class Hotels*/
#JacksonXmlRootElement(localName = "hotels")
public class Hotels {
#JacksonXmlElementWrapper(useWrapping = false)
private List<Hotel> hotel;
//Other getters and setters
}
/**Class Hotel*/
#JacksonXmlRootElement(localName = "hotel")
public class Hotel {
#JacksonXmlProperty(localName = "basic-info")
private HotelBaseInfo hotelBaseInfo;
//Other getters and setters
}
/**Class HotelBaseInfo*/
public class HotelBaseInfo {
#JacksonXmlProperty(localName = "hotel-name")
private String hotelName;
#JacksonXmlElementWrapper(localName = "hotel-amenities")
private List<HotelAmenity> hotelAmenities;
//Other getters and setters
}
/**Class HotelAmenity*/
public class HotelAmenity {
private String category;
private String description;
#JacksonXmlElementWrapper(localName = "amenities")
private List<Amenities> amenity;
static class Amenities {
#JacksonXmlText
private String value;
}
//Other getters and setters
}
Here's what worked for me:
public class JacksonXmlParsing {
#JacksonXmlRootElement(localName = "hotels")
static class HotelSearchResponse {
#JacksonXmlElementWrapper(localName = "hotel")
private List<CTHotel> hotels;
//other properties and getters and setters
}
static class CTHotel {
#JacksonXmlProperty(localName = "hotel-name")
private String hotelName;
#JacksonXmlElementWrapper(localName = "hotel-amenities")
private List<HotelAmenity> hotelAmenities;
//other properties and getters and setters
}
static class HotelAmenity {
private String category;
private String description;
#JacksonXmlElementWrapper
private List<String> amenities;
//other properties and getters/setters
}
public static void main(String[] args) throws IOException {
XmlMapper xmlMapper = new XmlMapper();
File file = new File("./src/main/resources/file.xml");
HotelSearchResponse response = xmlMapper.readValue(file, HotelSearchResponse.class);
System.out.println(response);
}
}
Output:
HotelSearchResponse(hotels=[CTHotel(hotelName=Hotel XYZ, hotelAmenities=[HotelAmenity(category=F&B, description=Random Text, amenities=[Cafe, Bar, Rastaurant])])])
But basic-info tag is missed, I could find out why.

Spring HATEOAS with nested resources and JsonView filtering

I am trying to add HATEOAS links with Resource<>, while also filtering with #JsonView. However, I don't know how to add the links to nested objects.
In the project on on Github, I've expanded on this project (adding in the open pull request to make it work without nested resources), adding the "Character" entity which has a nested User.
When accessing the ~/characters/resource-filtered route, it is expected that the nested User "player" appear with the firstNm and bioDetails fields, and with Spring generated links to itself, but without the userId and lastNm fields.
I have the filtering working correctly, but I cannot find an example of nested resources which fits with the ResourceAssembler paradigm. It appears to be necessary to use a ResourceAssembler to make #JsonView work.
Any help reconciling these two concepts would be appreciated. If you can crack it entirely, consider sending me a pull request.
User.java
//package and imports
...
public class User implements Serializable {
#JsonView(UserView.Detail.class)
private Long userId;
#JsonView({ UserView.Summary.class, CharacterView.Summary.class })
private String bioDetails;
#JsonView({ UserView.Summary.class, CharacterView.Summary.class })
private String firstNm;
#JsonView({ UserView.Detail.class, CharacterView.Detail.class })
private String lastNm;
public User(Long userId, String firstNm, String lastNm) {
this.userId = userId;
this.firstNm = firstNm;
this.lastNm = lastNm;
}
public User(Long userId) {
this.userId = userId;
}
...
// getters and setters
...
}
CharacterModel.java
//package and imports
...
#Entity
public class CharacterModel implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonView(CharacterView.Summary.class)
private Long characterId;
#JsonView(CharacterView.Detail.class)
private String biography;
#JsonView(CharacterView.Summary.class)
private String name;
#JsonView(CharacterView.Summary.class)
private User player;
public CharacterModel(Long characterId, String name, String biography, User player) {
this.characterId = characterId;
this.name = name;
this.biography = biography;
this.player = player;
}
public CharacterModel(Long characterId) {
this.characterId = characterId;
}
...
// getters and setters
...
}
CharacterController.java
//package and imports
...
#RestController
#RequestMapping("/characters")
public class CharacterController {
#Autowired
private CharacterResourceAssembler characterResourceAssembler;
...
#JsonView(CharacterView.Summary.class)
#RequestMapping(value = "/resource-filtered", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public Resource<CharacterModel> getFilteredCharacterWithResource() {
CharacterModel model = new CharacterModel(1L, "TEST NAME", "TEST BIOGRAPHY", new User(1L, "Fred", "Flintstone"));
return characterResourceAssembler.toResource(model);
}
...
}
CharacterResourceAssembler.java
//package and imports
...
#Component
public class CharacterResourceAssembler implements ResourceAssembler<CharacterModel, Resource<CharacterModel>>{
#Override
public Resource<CharacterModel> toResource(CharacterModel user) {
Resource<CharacterModel> resource = new Resource<CharacterModel>(user);
resource.add(linkTo(CharacterController.class).withSelfRel());
return resource;
}
}

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

I have model class like this, for hibernate
#Entity
#Table(name = "user", catalog = "userdb")
#JsonIgnoreProperties(ignoreUnknown = true)
public class User implements java.io.Serializable {
private Integer userId;
private String userName;
private String emailId;
private String encryptedPwd;
private String createdBy;
private String updatedBy;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "UserId", unique = true, nullable = false)
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
#Column(name = "UserName", length = 100)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "EmailId", nullable = false, length = 45)
public String getEmailId() {
return this.emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
#Column(name = "EncryptedPwd", length = 100)
public String getEncryptedPwd() {
return this.encryptedPwd;
}
public void setEncryptedPwd(String encryptedPwd) {
this.encryptedPwd = encryptedPwd;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "UpdatedBy", length = 100)
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
In Spring MVC controller, using DAO, I am able to get the object. and returning as JSON Object.
#Controller
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
#ResponseBody
public User getUser(#PathVariable Integer userId) throws Exception {
User user = userService.get(userId);
user.setCreatedBy(null);
user.setUpdatedBy(null);
return user;
}
}
View part is done using AngularJS, so it will get JSON like this
{
"userId" :2,
"userName" : "john",
"emailId" : "john#gmail.com",
"encryptedPwd" : "Co7Fwd1fXYk=",
"createdBy" : null,
"updatedBy" : null
}
If I don't want to set encrypted Password, I will set that field also as null.
But I don't want like this, I dont want to send all fields to client side. If I dont want password, updatedby, createdby fields to send, My result JSON should be like
{
"userId" :2,
"userName" : "john",
"emailId" : "john#gmail.com"
}
The list of fields which I don't want to send to client coming from other database table. So it will change based on the user who is logged in. How can I do that?
I hope You got my question.
Add the #JsonIgnoreProperties("fieldname") annotation to your POJO.
Or you can use #JsonIgnore before the name of the field you want to ignore while deserializing JSON. Example:
#JsonIgnore
#JsonProperty(value = "user_password")
public String getUserPassword() {
return userPassword;
}
GitHub example
Can I do it dynamically?
Create view class:
public class View {
static class Public { }
static class ExtendedPublic extends Public { }
static class Internal extends ExtendedPublic { }
}
Annotate you model
#Document
public class User {
#Id
#JsonView(View.Public.class)
private String id;
#JsonView(View.Internal.class)
private String email;
#JsonView(View.Public.class)
private String name;
#JsonView(View.Public.class)
private Instant createdAt = Instant.now();
// getters/setters
}
Specify the view class in your controller
#RequestMapping("/user/{email}")
public class UserController {
private final UserRepository userRepository;
#Autowired
UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
#RequestMapping(method = RequestMethod.GET)
#JsonView(View.Internal.class)
public #ResponseBody Optional<User> get(#PathVariable String email) {
return userRepository.findByEmail(email);
}
}
Data example:
{"id":"5aa2496df863482dc4da2067","name":"test","createdAt":"2018-03-10T09:35:31.050353800Z"}
UPD: keep in mind that it's not best practice to use entity in response. Better use different DTO for each case and fill them using modelmapper
I know I'm a bit late to the party, but I actually ran into this as well a few months back. All of the available solutions weren't very appealing to me (mixins? ugh!), so I ended up creating a new library to make this process cleaner. It's available here if anyone would like to try it out: https://github.com/monitorjbl/spring-json-view.
The basic usage is pretty simple, you use the JsonView object in your controller methods like so:
import com.monitorjbl.json.JsonView;
import static com.monitorjbl.json.Match.match;
#RequestMapping(method = RequestMethod.GET, value = "/myObject")
#ResponseBody
public void getMyObjects() {
//get a list of the objects
List<MyObject> list = myObjectService.list();
//exclude expensive field
JsonView.with(list).onClass(MyObject.class, match().exclude("contains"));
}
You can also use it outside of Spring:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import static com.monitorjbl.json.Match.match;
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
mapper.writeValueAsString(JsonView.with(list)
.onClass(MyObject.class, match()
.exclude("contains"))
.onClass(MySmallObject.class, match()
.exclude("id"));
Yes, you can specify which fields are serialized as JSON response and which to ignore.
This is what you need to do to implement Dynamically ignore properties.
1) First, you need to add #JsonFilter from com.fasterxml.jackson.annotation.JsonFilter on your entity class as.
import com.fasterxml.jackson.annotation.JsonFilter;
#JsonFilter("SomeBeanFilter")
public class SomeBean {
private String field1;
private String field2;
private String field3;
// getters/setters
}
2) Then in your controller, you have to add create the MappingJacksonValue object and set filters on it and in the end, you have to return this object.
import java.util.Arrays;
import java.util.List;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
#RestController
public class FilteringController {
// Here i want to ignore all properties except field1,field2.
#GetMapping("/ignoreProperties")
public MappingJacksonValue retrieveSomeBean() {
SomeBean someBean = new SomeBean("value1", "value2", "value3");
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("field1", "field2");
FilterProvider filters = new SimpleFilterProvider().addFilter("SomeBeanFilter", filter);
MappingJacksonValue mapping = new MappingJacksonValue(someBean);
mapping.setFilters(filters);
return mapping;
}
}
This is what you will get in response:
{
field1:"value1",
field2:"value2"
}
instead of this:
{
field1:"value1",
field2:"value2",
field3:"value3"
}
Here you can see it ignores other properties(field3 in this case) in response except for property field1 and field2.
Hope this helps.
We can do this by setting access to JsonProperty.Access.WRITE_ONLY while declaring the property.
#JsonProperty( value = "password", access = JsonProperty.Access.WRITE_ONLY)
#SerializedName("password")
private String password;
Add #JsonInclude(JsonInclude.Include.NON_NULL) (forces Jackson to serialize null values) to the class as well as #JsonIgnore to the password field.
You could of course set #JsonIgnore on createdBy and updatedBy as well if you always want to ignore then and not just in this specific case.
UPDATE
In the event that you do not want to add the annotation to the POJO itself, a great option is Jackson's Mixin Annotations. Check out the documentation
I've solved using only #JsonIgnore like #kryger has suggested.
So your getter will become:
#JsonIgnore
public String getEncryptedPwd() {
return this.encryptedPwd;
}
You can set #JsonIgnore of course on field, setter or getter like described here.
And, if you want to protect encrypted password only on serialization side (e.g. when you need to login your users), add this #JsonProperty annotation to your field:
#JsonProperty(access = Access.WRITE_ONLY)
private String encryptedPwd;
More info here.
If I were you and wanted to do so, I wouldn't use my User entity in Controller layer.Instead I create and use UserDto (Data transfer object) to communicate with business(Service) layer and Controller.
You can use Apache BeanUtils(copyProperties method) to copy data from User entity to UserDto.
I have created a JsonUtil which can be used to ignore fields at runtime while giving a response.
Example Usage :
First argument should be any POJO class (Student) and ignoreFields is comma seperated fields you want to ignore in response.
Student st = new Student();
createJsonIgnoreFields(st,"firstname,age");
import java.util.logging.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
public class JsonUtil {
public static String createJsonIgnoreFields(Object object, String ignoreFields) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(Object.class, JsonPropertyFilterMixIn.class);
String[] ignoreFieldsArray = ignoreFields.split(",");
FilterProvider filters = new SimpleFilterProvider()
.addFilter("filter properties by field names",
SimpleBeanPropertyFilter.serializeAllExcept(ignoreFieldsArray));
ObjectWriter writer = mapper.writer().withFilters(filters);
return writer.writeValueAsString(object);
} catch (Exception e) {
//handle exception here
}
return "";
}
public static String createJson(Object object) {
try {
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
return writer.writeValueAsString(object);
}catch (Exception e) {
//handle exception here
}
return "";
}
}
I've found a solution for me with Spring and jackson
First specify the filter name in the entity
#Entity
#Table(name = "SECTEUR")
#JsonFilter(ModelJsonFilters.SECTEUR_FILTER)
public class Secteur implements Serializable {
/** Serial UID */
private static final long serialVersionUID = 5697181222899184767L;
/**
* Unique ID
*/
#Id
#JsonView(View.SecteurWithoutChildrens.class)
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#JsonView(View.SecteurWithoutChildrens.class)
#Column(name = "code", nullable = false, length = 35)
private String code;
/**
* Identifiant du secteur parent
*/
#JsonView(View.SecteurWithoutChildrens.class)
#Column(name = "id_parent")
private Long idParent;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name = "id_parent")
private List<Secteur> secteursEnfants = new ArrayList<>(0);
}
Then you can see the constants filters names class with the default FilterProvider used in spring configuration
public class ModelJsonFilters {
public final static String SECTEUR_FILTER = "SecteurFilter";
public final static String APPLICATION_FILTER = "ApplicationFilter";
public final static String SERVICE_FILTER = "ServiceFilter";
public final static String UTILISATEUR_FILTER = "UtilisateurFilter";
public static SimpleFilterProvider getDefaultFilters() {
SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAll();
return new SimpleFilterProvider().setDefaultFilter(theFilter);
}
}
Spring configuration :
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = "fr.sodebo")
public class ApiRootConfiguration extends WebMvcConfigurerAdapter {
#Autowired
private EntityManagerFactory entityManagerFactory;
/**
* config qui permet d'éviter les "Lazy loading Error" au moment de la
* conversion json par jackson pour les retours des services REST<br>
* on permet à jackson d'acceder à sessionFactory pour charger ce dont il a
* besoin
*/
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
// config d'hibernate pour la conversion json
mapper.registerModule(getConfiguredHibernateModule());//
// inscrit les filtres json
subscribeFiltersInMapper(mapper);
// config du comportement de json views
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
converter.setObjectMapper(mapper);
converters.add(converter);
}
/**
* config d'hibernate pour la conversion json
*
* #return Hibernate5Module
*/
private Hibernate5Module getConfiguredHibernateModule() {
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Hibernate5Module module = new Hibernate5Module(sessionFactory);
module.configure(Hibernate5Module.Feature.FORCE_LAZY_LOADING, true);
return module;
}
/**
* inscrit les filtres json
*
* #param mapper
*/
private void subscribeFiltersInMapper(ObjectMapper mapper) {
mapper.setFilterProvider(ModelJsonFilters.getDefaultFilters());
}
}
Endly I can specify a specific filter in restConstoller when i need....
#RequestMapping(value = "/{id}/droits/", method = RequestMethod.GET)
public MappingJacksonValue getListDroits(#PathVariable long id) {
LOGGER.debug("Get all droits of user with id {}", id);
List<Droit> droits = utilisateurService.findDroitsDeUtilisateur(id);
MappingJacksonValue value;
UtilisateurWithSecteurs utilisateurWithSecteurs = droitsUtilisateur.fillLists(droits).get(id);
value = new MappingJacksonValue(utilisateurWithSecteurs);
FilterProvider filters = ModelJsonFilters.getDefaultFilters().addFilter(ModelJsonFilters.SECTEUR_FILTER, SimpleBeanPropertyFilter.serializeAllExcept("secteursEnfants")).addFilter(ModelJsonFilters.APPLICATION_FILTER,
SimpleBeanPropertyFilter.serializeAllExcept("services"));
value.setFilters(filters);
return value;
}
Place #JsonIgnore on the field or its getter, or create a custom dto
#JsonIgnore
private String encryptedPwd;
or as mentioned above by ceekay annotate it with #JsonProperty where access attribute is set to write only
#JsonProperty( value = "password", access = JsonProperty.Access.WRITE_ONLY)
private String encryptedPwd;
Can I do it dynamically?
Yes, you can use a combination of Jackson's PropertyFilter and mixins.
Explanation
Jackson has a PropertyFilter interface to implement a filter to ignore fields dynamically. The problem is that filter has to be defined on the DTO/POJO class using the #JsonFilter annotation.
To avoid adding a #JsonFilter on class we can use ObjectMapper's addMixIn method to "dynamically" add this annotation (and leave our DTO/POJO classes as is).
Code example
Here is my implementation of the idea provided above. We can call toJson() with two arguments: (1) object to be serialized and (2) lambda (Java's Predicate) to be used in PropertyFilter:
public class JsonService {
public String toJson(Object object, Predicate<PropertyWriter> filter) {
ObjectMapper mapper = new ObjectMapper();
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter("DynamicFilter", new DynamicFilter(filter));
mapper.setFilterProvider(filterProvider);
mapper.addMixIn(object.getClass(), DynamicFilterMixin.class);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new MyException(e);
}
}
private static final class DynamicFilter extends SimpleBeanPropertyFilter {
private Predicate<PropertyWriter> filter;
private DynamicFilter(Predicate<PropertyWriter> filter) {
this.filter = filter;
}
protected boolean include(BeanPropertyWriter writer) {
return include((PropertyWriter) writer);
}
protected boolean include(PropertyWriter writer) {
return filter.test(writer);
}
}
#JsonFilter("DynamicFilter")
private interface DynamicFilterMixin {
}
}
Now we can call toJson and filter fields during a serialization:
Filtering by name
new JsonService().toJson(object, w -> !w.getName().equals("fieldNameToBeIgnored"));
Filtering by annotation (on the field)
new JsonService().toJson(object, w -> w.getAnnotation(MyAnnotation.class) == null);
Unit tests
Here are the unit tests for the class above:
public class JsonServiceTest {
private JsonService jsonService = new JsonService();
#Test
public void withoutFiltering() {
MyObject object = getObject();
String json = jsonService.toJson(object, w -> true);
assertEquals("{\"myString\":\"stringValue\",\"myInteger\":10,\"myBoolean\":true}", json);
}
#Test
public void filteredByFieldName() {
MyObject object = getObject();
String json = jsonService.toJson(object, w -> !w.getName().equals("myString"));
assertEquals("{\"myInteger\":10,\"myBoolean\":true}", json);
}
#Test
public void filteredByAnnotation() {
MyObject object = getObject();
String json = jsonService.toJson(object, w -> w.getAnnotation(Deprecated.class) == null);
assertEquals("{\"myString\":\"stringValue\",\"myInteger\":10}", json);
}
private MyObject getObject() {
MyObject object = new MyObject();
object.myString = "stringValue";
object.myInteger = 10;
object.myBoolean = true;
return object;
}
private static class MyObject {
private String myString;
private int myInteger;
#Deprecated
private boolean myBoolean;
public String getMyString() {
return myString;
}
public void setMyString(String myString) {
this.myString = myString;
}
public int getMyInteger() {
return myInteger;
}
public void setMyInteger(int myInteger) {
this.myInteger = myInteger;
}
public boolean isMyBoolean() {
return myBoolean;
}
public void setMyBoolean(boolean myBoolean) {
this.myBoolean = myBoolean;
}
}
}
Would not creating a UserJsonResponse class and populating with the wanted fields be a cleaner solution?
Returning directly a JSON seems a great solution when you want to give all the model back. Otherwise it just gets messy.
In the future, for example you might want to have a JSON field that does not match any Model field and then you're in a bigger trouble.
This is a clean utility tool for the above answer :
#GetMapping(value = "/my-url")
public #ResponseBody
MappingJacksonValue getMyBean() {
List<MyBean> myBeans = Service.findAll();
MappingJacksonValue mappingValue = MappingFilterUtils.applyFilter(myBeans, MappingFilterUtils.JsonFilterMode.EXCLUDE_FIELD_MODE, "MyFilterName", "myBiggerObject.mySmallerObject.mySmallestObject");
return mappingValue;
}
//AND THE UTILITY CLASS
public class MappingFilterUtils {
public enum JsonFilterMode {
INCLUDE_FIELD_MODE, EXCLUDE_FIELD_MODE
}
public static MappingJacksonValue applyFilter(Object object, final JsonFilterMode mode, final String filterName, final String... fields) {
if (fields == null || fields.length == 0) {
throw new IllegalArgumentException("You should pass at least one field");
}
return applyFilter(object, mode, filterName, new HashSet<>(Arrays.asList(fields)));
}
public static MappingJacksonValue applyFilter(Object object, final JsonFilterMode mode, final String filterName, final Set<String> fields) {
if (fields == null || fields.isEmpty()) {
throw new IllegalArgumentException("You should pass at least one field");
}
SimpleBeanPropertyFilter filter = null;
switch (mode) {
case EXCLUDE_FIELD_MODE:
filter = SimpleBeanPropertyFilter.serializeAllExcept(fields);
break;
case INCLUDE_FIELD_MODE:
filter = SimpleBeanPropertyFilter.filterOutAllExcept(fields);
break;
}
FilterProvider filters = new SimpleFilterProvider().addFilter(filterName, filter);
MappingJacksonValue mapping = new MappingJacksonValue(object);
mapping.setFilters(filters);
return mapping;
}
}
To acheive dynamic filtering follow the link - https://iamvickyav.medium.com/spring-boot-dynamically-ignore-fields-while-converting-java-object-to-json-e8d642088f55
Add the #JsonFilter("Filter name") annotation to the model class.
Inside the controller function add the code:-
SimpleBeanPropertyFilter simpleBeanPropertyFilter =
SimpleBeanPropertyFilter.serializeAllExcept("id", "dob");
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter("Filter name", simpleBeanPropertyFilter);
List<User> userList = userService.getAllUsers();
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(userList);
mappingJacksonValue.setFilters(filterProvider);
return mappingJacksonValue;
make sure the return type is MappingJacksonValue.
Hi I have achieved dynamic filtering by using Gson library like in the below:
JsonObject jsonObj = new Gson().fromJson(mapper.writeValueAsString(sampleObject), JsonObject.class);
jsonObj.remove("someProperty");
String data = new Gson().toJson(jsonObj);
In your entity class add #JsonInclude(JsonInclude.Include.NON_NULL) annotation to resolve the problem
it will look like
#Entity
#JsonInclude(JsonInclude.Include.NON_NULL)

Categories