I am wondering about the possibility of field name serialization in MongoDB using Spring data. What I meant in field name serialization is, let's say I have a field called 'projectName' and I want to store this field name as it is in MongoDB but when it is converted to JSON, I want it to be 'project_name'.
I know that I can do this through MongoConverter, but I am wondering is there an annotation like Gson's #SerializedName so I do not have to do conversions for entire classes just because of field names.
As I mentioned earlier, I am using Spring data to work with MongoDB.
Please note that I am aware about #Field annotation which converts the POJO field name into a custom MongoDB field name which I do not need in this case.
Thanks in advance!
Related
How do I create a field of data type varchar in my controller class with size as 20?
Also, could anyone please tell me how to create a field of data type none. Also, how to mention the fields to be mandatory?
I am quite beginner in this. Any help would be appreciated.
you cannot declare varchar in controller you have to use String
private String str = ""; or you can use this
StringBuilder str
= new StringBuilder();
str.setLength(20);
Ok, so your question is lacking context so I am going to make some assumptions. I'm assuming that you have to implement some controller that exposes an URL endpoint. I assume that you want to be able to receive data on that endpoint and map it to an object (dto). I assume that you want to assure that you want to perform validitions on the received data.
Im on my phone so I won't write it out completely but let me give you some pointers.
Create a dto object with the data structure that you're expecting to receive.
Create a contreoller with #Controller annotation.
Within the controller, create a method with the #postMapping annotation and configure it appropriately. The method should accept the dto class and a binding result class as method parameter. Within the method definition use the #Valid annotation before the dto class. The informs Spring to validate the dto and it will inject the valdition result into the Binding Result object. Note that the latter should be mentioned after the dto, in this example it would be the second and last parameter.
Now in the dto, you can annotate the class fields with annotations from the javax.validation package. For example #NotNull or #Size which could assert the size of a string field and assure the availability of a field value. Note that I believe in later versions of Java, the validation package was moved to Jakarta package so take that into consideration. Also make sure to use the right annotations, for example there is also #Nonnull from spring which does other stuff.
Now, within the method body you can now assert if there where any binding result errors. Just check the BindingResult.hasErrors() and then handle them appropriately.
The field of data type None does not ammake sense to me so will need more information to be able to help with that.
This seems like it would be a really common thing to need in just about any Java project. And yet I am unable to find anything that serves this purpose.
I used to use a web framework called Stripes Framework, that had annotation driven validators and automatic formatting via their validator API.
Example:
#Validate(maxlength = ModelConstants.NAME_MAX_LENGTH, converter = CapitializeFullyTypeConverter.class)
private String name;
#Validate(maxlength = ModelConstants.NAME_MAX_LENGTH, converter = EmailTypeConverter.class)
private String email;
Those fields would be defined on your controller action bean, and all user input would automatically be validated and formatted according to the specified rules.
If someone would enter their email address as: "TEST#TEST.COM"
Then it would automatically be formatted to: "test#test.com"
I would like to find something like this for automatically formatting data within DTOs.
If nothing like this is available, what is the usual way of handling this? Surely everyone is not writing custom formatting functions for each getter within the DTO?
Assumption: meaning of "formatter" as type-converter
When you ask for annotation based "formatter" you mean Stripe Framework's #Validate annotation with its parameter converter. The converter can be parameterized as:
(class) The converter class that will be used to transform this parameter into its object representation
In the Web-MVC context this means the converter is used to convert the request-parameter, exactly its source value, as supplied by the incomming web-request. The converted value is then stored as target value to the (DTO) object's property.
Example: Conversion of (DTO) Strings
Web request is given incommong with parameter name email and value string TEST#EXAMPLE.COM. This should the be converted to lowercase and strored in the DTO's property (a.k.a attribute or field ) email as value test#example.com.
Spring annotations for DTOs
Spring Framework also uses the concepts of request validation and request conversion. It also allows to configure these annotations-driven on the DTOs or classes and their attributes.
The validation leverages Java Bean Validation standard (JSR-303) javax.validation annotations like #Valid and #Length.
The conversion is part of the HttpConverters used for serialization/deserialization of responses/requests to/from objects (DTO). Therefore Spring allows to inlude object-relational mapper (ORM) frameworks or libraries as (e.g. Maven) dependencies. These bring their own annotations regarding conversation with them.
Fasterxml's Jackson
Jackson (ORM) for example uses the annotation #JsonFormat to achieve simple string conversions - but only for non-string fields like Date or Number (as far as I know).
It also allows complete customisation of serializers and deserializers via annotations #JsonSerialize and #JsonDeserialize.
Note, that although many annotations in Jackson are named with "Json" they mostly also apply to XML or even other data formats (representations) like CSV, etc.
String To Lowercase with Jackson
Your question was asked for Jackson: How to force Jackson deserialize field values to lower case and answered.
See also
Difference between #Valid and #Validated in Spring
Use Jackson to deserialize JSON string or object into a String field
DZone: Tutorial on Jackson Deserialization Annotations
Bealdung (2019): Getting Started with Custom Deserialization in Jackson
If you are using Spring Mvc, you have access to a formatting API.
There are pre-existing annotations in the org.springframework.format.annotation package for date and number formatting.
If you need custom formatting rules, you can write your own and register it via the FormattingConversionServiceFactoryBean.
See some examples here: https://docs.spring.io/spring-framework/docs/3.2.0.RC1/reference/html/validation.html
I am using #JsonProperty in a generic model Parser to extract classes from a feed.
The problem I'm having is that a specific property may have different types.
E.g: #JsonProperty("house") In some json files the house is a List<Rooms> and in the other is a Map<Rooms>, but the property name is always the same.
What can I do?
Thank you for your Help
I know there are numerous posts out there for a similar problem, but mine seems to be a bit different. I am reading in a bunch of JSON and would like to build POJO from it, but I don't want to use the names of the JSON result. Is there a way to "map" the element names in JSON to the attributes in my POJOs (using gson or Jackson maybe)?
It's worth mentioning this application is being built for Android.
Thanks in advance!
If you're using Gson, you can append an attribute to your objects, like so:
#SerializedName("ServicesResult")
public String services;
Where "ServicesResult" is the actual name of the element in the JSON.
With Jackson, you have multiple options:
Use #JsonProperty("name") annotation to indicate name to use in JSON, add directly or use mix-in annotations (external)
Specify PropertyNamingStrategy to convert from "Java name" to "JSON name" (there is default java<->c-style converter bundled with 1.9)
Modify AnnotationIntrospector to change the name using some other mechanism than annotations
Jackson will also interpret the Basic package javax.xml.bind.annotation
If you use those annotations you can readily move between Json/XML
I have an Java class, like Library, that contains many fields. I want do ajax call to server
and in controller's method I want to have partly initialized #RequestBody Library with only
fields, which are present in json object.
I read the http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/, but I need not full object.
Please Help
You could use a org.codehaus.jettison.json.JSONObject (part of the Jettison project) and only include the fields that you need.
Or, you could just make a simplified version of Library that includes only the fields that you want (call it AjaxLibrary or something).
It would not be a problem to use full object, cause fields would not be initialized, if they are not present at entire json.
Also you can create own DTO class, e.g. SomeActionLibraryDTO. Extract required fields from Library, and use #JsonIgnoreProperties(ignoreUnknown = true) annotation for class to ignore the rest of json object (I suppose you are using the default json jackson marshaller, right?)