POJO requirement question - java

Reading some articles, it is best to have POJO object to do JSON or XML serialization. I am wondering whether POJO can have construtors or methods?

"POJO" is a terrible name, but basically, yes, a Javabean class representing an entity would be extremely helpful in doing the JSON or XML serialization since there are so many API's out which understands Javabeans and can convert between them and the desired format in a single code line. Last but not least, you can reuse the same Javabean class in all other layers of your application. E.g. to store data in a DB, or to transfer the data between layers, or to present the data to the enduser, etc.
And surely such a class can have constructors and methods.
See also:
Places where Javabeans are used
Converting JSON to Java

Related

Java serialization to string

I have the following declaration of the static type Object:
Integer typeId;
//Obtaining typeId
Object containerObject = ContainerObjectFactory.create(typeId);
The factory can produce different types of container objects, e.g. Date, Integer, BigDecimal and so forth.
Now, after creating the containerObejct I need to serialize it to an object of type String and store it into a database with hibernate. I'm not going to provide Object-relational mapping because it doesn't relate to the question directly.
Well, what I want to do is to serialize the containerObject depending on it runtime-type and desirialize it later with the type it was serialized. Is it ever possible? Could I use xml-serialization for those sakes?
There are numerous alternatives, and your question is quite broad. You could:
use the native Java serialisation, which is binary, and then Base64 encode it
use an XML serialisation library, such as XStream
use a JSON serialisation library, such as Gson
One key feature you mention is that the object type needs to be embedded in the serialised data. Native Java serialisation embeds the type in the data so this is a good candidate. This is a double-edged sword however, as this makes the data brittle - if at some time in the future you changed the fully qualified class name then you'd no longer be able to deserialise the object.
Gson, on the other hand, doesn't embed the type information, and so you'd have to store both the JSON and the object type in order to deserialise the object.
XML and JSON have advantages that they're a textual format, so even without deserialising it, you can use your human eyes to see what it is. Base64 encoded Java serialisation however, is an unintelligible blob of characters.
There are multiple ways, but you need custom serialization scheme, e.g.:
D|25.01.2015
I|12345
BD|123456.123452436
where the first part of the String represents the type and the second part represents the data. You can even use some binary serialization scheme for this.

Is there a good "standard" Java interface for XML and JSON readers/writers?

Basically, I want to have an interface for converting Objects to/from their XML or JSON String representation, something like
public interface IStringifier{
/**
Converts the Object to it's String representation, e.g. XML or JSON
*/
public String toString(Object o);
/**
Converts from the String representation (e.g. XML or JSON) to an Object
*/
public Object fromString(String s, Class<?> clazz);
}
Such an interface would be fairly simple to implement in GSON, XStream etc. but by abstracting it you are abstracted from knowing just what is going on underneath. And you are decoupled from one of the many many XML or JSON libraries, so clients are freer to pick their favorite.
Is there any "standard" Java interface for this? Something in Guava, Apache, etc?
(added) None of the answers were what I really wanted ("yes, in javax.obscure.interfaces there's what you want") but thanks for the replies. I'll accept Tom's answer as the most informative/provocative. And maybe I'll clean up the code I have and try to create a standard. :-)
JAXB (JSR-222) is the Java SE/EE standard for converting objects to/from XML. It can be used standalone and is the standard binding layer for JAX-WS (SOAP) and JAX-RS (RESTful) Web Services. Below is a link to an example of specifying an alternate provider via a jaxb.properties file.
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
There currently isn't a standard API for JSON binding.
I think you're overthinking this. You don't actually care about turning objects into Strings, you want to be able to serialize objects to different formats without knowing what that format is. But who says that different format is a String? What happens when you want your object to be available as a protocol buffer? That's a binary format, not a character format -- so stringify() won't help there. Ultimately, it's up to you to architect your application to be as independent as possible of those details.
XML and JSON are unrelated, so this is actually two questions:
For JSON, although "unofficial", a popular library is GSON.
For XML, see Blaise's answer
One popular JSON-to-Java binding library is Jackson
One popular XML-to-Java binding library is XStream
If you intend to use this in a web application, maybe you would like to consider Spring 3 MVC's facilities for this. Through annotations it does the conversion automatically and you can tell it whether you want XML or JSON (or various other formats). This might be the common interface you are looking for too.

Best practice: Java/XML serialization: how to determine to what class to deserialize?

I have an application that saves its context to XML. In this application, there is a hierarchy of classes, that all implement a common interface, and that represent different settings. For instance, a first setting class may be made of 4 public float fields, another one can be made of a sole HashMap.
I am trying to determine what is the best way to handle writing and reading to XML in a generic way. I read on this site a lot about JAXB and XStream for instance, which are able to make a specific class instance from XML.
However my question is related to the fact that the actual class can be anything that implement a given interface. When you read the XML file, how would you guess the actual class to instantiate from the XML data? How do you do that in your applications?
I thought that I could write the .class name in a XML attribute, read it and compare it to all possible class .class names, until I find a match. Is there a more sensible way?
Thanks
xstream should already take care of this and create the object of correct type.
The tutorial seems to confirm that:
To reconstruct an object, purely from the XML:
Person newJoe = (Person)xstream.fromXML(xml);
If you don't know the type, you will have to first assign it to the common interface type:
CommonInterface newObject = (CommonInterface)xstream.fromXML(xml);
// now you can either check its type or call virtual methods
In my case I just have a kind of header that stores the class name that is serialized and when de-serializing it I just use the header value to figure out to which class shall I de-serialize the values.
A best practice would to use an established, well documented XML parser/mapper. All of the serialization/deserialization work has been done, so you can worry about your business logic instead. Castor and Apache Axiom are two APIs that I have used to marshal/unmarshall(serialize/deserialize) Java Classes and XML.
http://www.castor.org
Apache Axiom

JAXB - Add a node to the XML as html link

I have a basic JavaBean in my service layer and originally it was not designed for marshalling. This object is used by both JAX-WS, JAX-RS, and Servlets in other layers of my application. I want to take advantage of a drill down type effect in my REST services so my question is: How do I make one of the fields/properties of the javabean appear in the xml as an HTML Link? Obviously I need to use CData. I cannot modify the original javabean by adding fields, etc. Is there an annotation I can use?
If I have in my class:
...
String data;
...
how do I make that(in xml):
<data><![CDATA[ValueOfData]]></data>
is this possible with JAXB and Annotations? Maybe xlink?
I suggest using a type adapter. These are normally used to adapt XML string values into more strongly-typed values like timestamps, but you can also use them to adapt strings to strings.
First, create a subclass of javax.xml.bind.annotation.adapters.XmlAdapter. This class will have to implement marshal and unmarshal, converting to and from the value of your field, and the HTML fragment in the XML.
Once you have that, you can annotate your field with
#XmlJavaTypeAdapter(MyAdapter.class)
And that should be it.

What is the difference between POJO (Plain Old Java Object) and DTO (Data Transfer Object)?

I cannot find difference between them. Does anyone know how to differentiate them?
POJO or "Plain Old Java Object" is a name used to describe "ordinary" Java objects, as opposed to EJBs (originally) or anything considered "heavy" with dependencies on other technologies.
DTO or "Data Transfer Object" is an object for... well... transferring data, usually between your "business" classes and persistence layer. It typically is a behavior-less class much like a C-style struct. They are an outdated concept.
A POJO is just a simple Java object, the acronym is used to emphasize that it really is nothing special.
A DTO is a Data Transfer Object which is used to encapsulate data that is transferred over a connection between layers or subsystems. See the wikipedia article, it's also a Core J2EE pattern (http://www.oracle.com/technetwork/java/transferobject-139757.html).
http://en.wikipedia.org/wiki/Data_transfer_object
All DTOs are POJOs, but not all POJOs are DTOs. An example of POJO that is not a DTO is a business class that contains state and behavior (business logic).
DTO (Data transfer object) : Is a Core J2EE design pattern used for transferring data within the system.DTO Pattern
POJO (Plain Old Java Object) : It is just an acronym people use for suggesting that is a simple java object (which nowadays is heavily annotated for doing some meaning full work).
DTO Pattern
J2EE Pattern Catalog
DTO is pojo, but pojo is not dto, because pojo can have more behavior but DTO just basically no behavior
Oracle document has clear description.
A POJO can have behavior. The book POJOs in Action details use of POJOS for application development.
DTOs are data containers that help transfer data from one layer to another. DTOs aren't supposed to contain any behavior.
I could understand the difference between POJO and DTO from this sentence of DTO's wiki:
DTOs are simple objects that should not contain any business logic but may contain serialization and deserialization mechanisms for transferring data over the wire.
Also, DTO is perfectly visualized and described in detail in Martin Fowler's Catalog of Patterns of Enterprise Application Architecture
POJO = Plain Old Java Object
DTO = Data Transfer Object
-- Edit
Well, this is assuming you don't know what the acronyms mean. A Pojo is just an object that is free from any sort of inheritance chain. A DTO exists in your data model, so probably follows a strict chain relating it to a given entity.

Categories