I have a RESTapi written using Jersey Framework. Along with it there is a POJO class. Now, my need is how do I make a particular field optional in my POJO so that the api will work regardless of that optional field? I want the API should work in both the cases, i.e
if I give that optional parameter then also,
if I don't give then also it should work.
Java 8's Optional was mainly intended for return values from methods, and not for data properties of Java classes(POJO), as described in Optional in Java SE 8:
Of course, people will do what they want. But we did have a clear
intention when adding this feature, and it was not to be a general
purpose Maybe or Some type, as much as many people would have liked us
to do so. Our intention was to provide a limited mechanism for library
method return types where there needed to be a clear way to represent
"no result", and using null for such was overwhelmingly likely to
cause errors.
The key here is the focus on use as a return type. The class is
definitively not intended for use as a property of a Java Bean.
Witness to this is that Optional does not implement Serializable,
which is generally necessary for widespread use as a property of an
object.
[credits] : https://blog.joda.org/2014/11/optional-in-java-se-8.html
I'm guessing you are referring to the serialisation of fields in your POJO. Since you have not stated which version of jackson you are using, you'll have to use one of these annotations to allow nulls:
Can be used on either class or getter:
#JsonInclude(Include.NON_NULL)
If you are using Jackson <2.x, use this:
#JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
Related
I am using a third-party library that defines an Option class, which is similar to java.util.Optional. In one case, it holds a type that needs a custom deserializer. With Optional, I could write
class StdContainer {
#JsonDeserialize(contentUsing=MyDeserializer.class)
#JsonSerialize(contentUsing=MySerializer.class)
Optional<MyClass> content;
}
and Jackson will using my custom serializer/deserializer on the class.
With the third party library, I tried writing
class ThirdPartyContainer {
#JsonDeserialize(contentUsing=MyDeserializer.class)
#JsonSerialize(contentUsing=MySerializer.class)
Option<MyClass> content;
}
This serializes MyClass using the default serializer, which makes sense, since I would not expect Jackson to know about the third-party library. Is there a way to tell Jackson that a particular class is a container and that it should use contentUsing on that class? I would expect that this also involves telling Jackson how to get the content.
The way Optionals (from Guava, Java 8, Scala) are recognized as containers is by them registering TypeModifier: this makes Jackson recognize them as somewhat special (actual type is ReferenceType).
To see how these work you could have a look at, say, jackson-datatype-guava. Once type is refined actual serializer/deserializer implementation is quite simple: jackson-databind has base implementations that provide about 90% of handling (see, for example AtomicReferenceSerializer and AtomicReferenceDeserializer in jackson-databind).
Use cases like these are actually big reason why Jackson module interface was added, to allow development and sharing of datatype modules for 3rd party types, so that once maintainers of a datatype lib (or community) provides such module, other users can simply plug it in and things "just work"
I realize this has probably been asked a hundred times but I have searched a lot and can't find specifically what I'm looking for.
Here is what I'd like. Given a string data, I'd like to deserialize into an object obj that doesn't have all the fields predefined. I'd like to just be able to ask for the fields I want such as obj.getString("stringFieldName") or obj.getInt("intFieldName"). I already have gson being used for other things so if it is possible with gson that would be great although not opposed to using another library.
The 'standard' Android JSON library (since API 1) already provides such untyped access.
See JSONObject, eg. getInt:
Returns the value mapped by name if it exists and is an int or can be coerced to an int, or throws otherwise.
Unless needing the JSON mapped onto a 'native' Java collection type this is probably the simplest way to achieve the request. It doesn't require any additional libraries.
With Jackson library you can annotate data model class with
#JsonIgnoreProperties(ignoreUnknown = true)
and the jacksonconverter will just parse only these fields that you defined. Other will be ignored.
Have you tried using Retrofit from Square? It works with GSON and Java Annotations and it's super easy to set up.
This question already has answers here:
Uses for Optional
(14 answers)
Guava Optional as method argument for optional parameters
(1 answer)
Closed 7 years ago.
I have read something about the purpose of Optional (unfortunately I don't remember where) in Java 8, and I was surprised the writer didn't mention the use of an Optional as an attribute in a class.
Since I am using optionals pretty frequently in my classes, I was wondering if this is a good practice. Or could I better just use normal attributes, which return null when they are not set?
Note: It may look like my question is opinion based, but I get the feeling using Optional in a class is really not the way to go (after reading the mentioned post). However, I like to use it and can't find any downside of using it.
Example
I would like to give an example to clarify. I have a class Transaction, which is built like this:
public class Transaction {
private Optional<Customer> = Optional.empty();
....
vs
public class Transaction {
private Customer = null;
....
When checking on a Customer, I think it is most logical to use transaction.getCustomer().isPresent() than transaction.getCustomer() != null. In my opinion the first code is cleaner than the second one.
Java 8's Optional was mainly intended for return values from methods, and not for properties of Java classes, as described in Optional in Java SE 8:
Of course, people will do what they want. But we did have a clear intention when adding this feature, and it was not to be a general purpose Maybe or Some type, as much as many people would have liked us to do so. Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.
The key here is the focus on use as a return type. The class is definitively not intended for use as a property of a Java Bean. Witness to this is that Optional does not implement Serializable, which is generally necessary for widespread use as a property of an object.
I think it is a theoretical question.
The notion of optional values was brought from functional languages world. Those languages usually also support pattern matching on language level and allow you to pattern match on the optional value.
In functional languages function calls usually return an optional value that other code could pattern match on.
I have never seen passing an optional as argument, but that does not mean it is a bad think. It looks weird though.
I'm using Jersey 1.x here and I have a #POST method that requires sending over a deeply nested, complex object. I'm not sure of all my options, but it seems like a lot are described in this documentation:
In general the Java type of the method parameter may:
Be a primitive type;
Have a constructor that accepts a single String argument;
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String) and
java.util.UUID.fromString(String)); or
Be List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.
Ideally, I wish that I could define a method like this:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Path("complexObject")
public void complexObject(#FormParam("complexObject") ComplexObject complexObject) throws Exception {
But I guess I can only do that if my object satisfies the requirements above (which in my case, it does not). To me it seems that I have a choice.
Option 1: Implement fromString
Implement item #3 above.
Option 2: Pass in the complexObject in pieces
Break up the complexObject into pieces so the parameters become this:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Path("complexObject")
public void complexObject(#FormParam("piece1") LessComplexPiece lessComplexPiece1,
#FormParam("piece2") LessComplexPiece lessComplexPiece2,
#FormParam("piece3") LessComplexPiece lessComplexPiece3) throws Exception {
This may not be enough if LessComplexPiece does not satisfy the requirements above. I'm wondering what the best option is here. What do people usually do in this situation? Here are the pros and cons I can think of:
Cons of Implement fromString
Have to maintain a custom deserializer. Every time the class is modified, this deserializer may break. There's more risk for bugs in general.
It will probably be impossible to generate documentation that describes the pieces of the complex object. I'll have to write that by hand.
For each piece of the complex object, I'll have to write my own casting and validation logic.
I'm not sure what the post data would look like. But, this may make it very difficult for someone to call the API from a web page form. If the resource accepted primitives, it would be easy. EG: complexObject=seralizedString vs firstName=John and lastName=Smith
You may not be able to modify the class for various reasons (thankfully, this is not a limitation for me)
Pros of Implementing fromString
This could avoid a method with a ton of parameters. This will make the API less intimidating to use.
This argument is at the level of abstraction I want to work at in the body of my method:
I won't have to combine the pieces together by hand (well technically I will, it'll just have to be in the deserializer method)
The deserializer can be a library that automates the process (XStream, gensen, etc.) and save me a lot of time. This can mitigate the bug risk.
You may run into "namespace" clashes if you flatten the object to send over pieces. For example, imagine sending over an Employee. If he has a Boss, you now have to provide a EmployeeFirstName and a BossFirstName. If you were just deserializing an object, you could nest the data appropriately and not have to include context in your parameter names.
So which option should I choose? Is there a 3rd option I'm not aware of?
I know that this question is old but in case anybody has this problem there is new better solution since JAX-RS 2.0. Solution is #BeanParam. Due to documentation:
The annotation that may be used to inject custom JAX-RS "parameter aggregator" value object into a resource class field, property or resource method parameter.
The JAX-RS runtime will instantiate the object and inject all it's fields and properties annotated with either one of the #XxxParam annotation (#PathParam, #FormParam ...) or the #Context annotation. For the POJO classes same instantiation and injection rules apply as in case of instantiation and injection of request-scoped root resource classes.
If you are looking for extended explanation on how this works please look at article I've found:
http://java.dzone.com/articles/new-jax-rs-20-%E2%80%93-beanparam
For complex object models, you may want to consider using JSON or XML binding instead of URL-encoded string to pass your objects to your resource call so you can rely on JAXB framework?
The Jersey Client library is compatible with JAXB and can handle all the marshaling transparently for you if you annotate your classes #XmlElementRoot.
For documentation, XSDs are a good starting point if you choose the XML binding.
Other REST documentation tools like enunciate can take the automatic generation to the next level.
What about special handler which transforms object to e.g. json - kryo if you would prefer performance? You got couple options
Look also at persistence ignorance.
I've just finished reading the chapter of 'Thinking in Java' concerning type information and reflection. While instanceof seems quite natural to me, some examples of reflection made me confused. I want to know if reflection is widely used in Java projects? What are 'the good parts' of reflection? Can you suggest any interesting lectures about reflection and type information with more good and worthy examples?
Edit (one more question):
Why is it useful to access private methods and fields withjava.lang.reflect.Method.setAccesible()?
Thanks in advance.
if you could post some of the examples I would be glad to explain it for you.
Reflection is wildly used with frameworks that need to extract meta-info about the running object (e.g. frameworks which depends on Annotations or the fields in your objets, think about Hibernate, Spring and a lot others).
On a higher layer, I sometimes use reflection to provide generic functionality (e.g. to encode every String in an object, emulate Duck Typing and such).
I know that you already read a book which covers the basics about reflection, but I need to point Sun (erm.. Oracle) official Tutorial as a must read: http://download.oracle.com/javase/tutorial/reflect/
One good example in my opinion is instantiating objects based on class names that are known only at runtime, for example contained in a configuration file.
You will still need to know a common interface to the classes you're dynamically instantiating, so you have something to cast them too. But this lets a configuration drive which implementation will be used.
Another example could be when you have to cast an object to a class that it's a descendant. If you are not sure about the type of that object, you can use instanceof to assure that the cast will be correct at runtime avoiding a class cast exception.
An example:
public void actionPerformed (ActionEvent e){
Object obj = e.getSource();
if (obj instanceof objType)
objType t = (objType) obj; // you can check the type using instanceof if you are not sure about obj class at runtime
}
The reason to provide such features in Reflection is due to multiple situations where tool/application needs meta information of class, variables, methods. For example:-
IDEs using auto completion functionality to get method names and attribute names.
Tomcat web container to forward the request to correct module by parsing their web.xml files and request URI.
JUnit uses reflection to enumerate all methods in a class; assuming either testXXX named methods as test methods or methods annoted by #Test.
To read full article about reflection you can check http://modernpathshala.com/Forum/Thread/Interview/308/give-some-examples-where-reflection-is-used