Serialization pojo into different json structure - java

I need to serialize a pojo into different json structure depending on whom I am sending request. Also I should be able to configure in some config that how field of pojo are mapped to json properties for a given request.
Can this be achived using jackson?
Is there some library or api to do this?
Edit:
For example:
public class Universal {
private int id;
private Date date;
private String name;
private Inner inner;
private Map<String,Object> others;
private List<Inner> inners;
}
public class Inner {
private String value;
}
now above are two object i need to create dynamic json, one example for some of transformation is below
{
"id":"",//value will be id of Universal
"detials":{
"name":"",//value will be name of Universal
},
"data":[], // array of value(field of Inner) from inners
"ext":{
"prop1":""// value of this field will be some (key1) value from others
}
}

You can use Google Gson and rely on its type adaptors.
http://www.javacreed.com/gson-typeadapter-example/ is a good article from web

Related

Use DTO to map JSON to final object, or just parse JSON?

I have some json object that looks like this:
{
"make":"Volvo",
"model":"240",
"metadata":{
"color":"white",
"year":"1986",
"previousOwner":"Joe",
"condition":"good"
}
}
And I want to turn this JSON into List<Car>, which is comprised of the following objects:
public class Car {
private String make;
private String model;
private CarMetadata carMetadata;
}
public class CarMetadata {
private Body body;
private History history;
}
public class Body {
private String color;
private String condition;
}
public class History {
private String previousOwner;
private String year;
}
So essentially the point is that the object I want to turn it into (Car) is very nested, whereas my JSON is not very nested. In reality the "Car" object is actually much more nested than this example I'm showing.
I was thinking of two options:
Create a CarDTO object to represent my input JSON, do objectMapper.readValue(json, CarDTO.class), then map CarDTO to Car to create my List<Car>.
Just parse the JSON and create the final List<Car> object in the first place.
I don't want to create an unnecessary DTO, but I also don't want to mess with parsing this JSON.
Is there a best practice in this scenario, and would this even be a valid use of a DTO?
Use a DTO.
Although you can deserialize from json directly to your domain class, their structure differs so you would have to create a custom deserializer... DO NOT TRY THIS AT HOME. I've been there and it's completely not worth the hassle.
Use the DTO to parse the json into a POJO, then map the DTO to the domain object.
This will decouple the transport from your domain object, allowing both to change freely with only the mapping code being affected. It's also way easier to write, understand, test and debug.

JPA / Jackson - Exclude fields when deserialize and include them when serialize

I have a JPA entity with a couple of fields (the real ones are more complex). I'm receiving some data via REST (POST operation in a Spring controller) and storing it right away in the JPA entities; I want to see if there is a possibility to exclude some field(s) when the request is sent, Jackson deserializes it, and constructs the object. But at the same time I want those fields to be included when I send back (object gets serialized) the response.
#Table("key_card")
public final class KeyCard {
private String username; // Don't want this to be sent as input,
// but want to be able to send it back
// in the response
#NotBlank
private final char[] password;
}
I'm just trying not to model it twice (for the request and response) if there is a way to solve this.
You can use JSON views: http://wiki.fasterxml.com/JacksonJsonView
Class Views {
static class AlwaysInclude { }
static class OnlyOnSerialize extends AlwaysInclude { }
}
And then on your view:
#Table("key_card")
public final class KeyCard {
#JsonView(Views.OnlyOnSerialize.class)
private String username;
#JsonView(Views.AlwaysInclude.class)
#NotBlank
private final char[] password;
}
To exclude a Java object property only from Json deserialization and to include instead its value during serialization you can use an appropriate combination of #JsonIgnore and #JsonProperty annotations.
In particular you should:
annotate with #JsonIgnore the property itself
annotate with #JsonIgnore its set method
annotate with #JsonProperty its get method
Here you can find an in-depth explanation and an example: Jackson: using #JsonIgnore and #JsonProperty annotations to exclude a property only from JSON deserialization

How to parse DTO to Pojo objects

Well, I'm trying to parse objects and I'm having so much issues.
My classes are like this:
-Entidad-
public class Entidad{
private Long codEntidad;
private Set<Comunicacion> comunicacion;
/*------------ Getter and Setters --------------*/
}
-Comunicacion-
public class Comunicacion {
private Entidad entidad;
private Long codComunicacion;
/*------------ Getter and Setters --------------*/
}
I need to parse to DTO objects:
-EntidadDTO-
public class EntidadDTO{
private Long codEntidad;
private Set<ComunicacionDTO> comunicacionDto;
/*------------ Getter and Setters --------------*/
}
-ComunicacionDTO-
public class ComunicacionDTO {
private EntidadDto entidadDto;
private Long codComunicacion;
/*------------ Getter and Setters --------------*/
}
I tried to use:
BeanUtils.copyProperties(entidad, entidadDto);
It seems that the parse is success but the property entidadDto.getComunicacionDto(); is a hashMap of Comunicacion (not ComunicacionDTO)
Should I try to make a custom parse with reflection?
Also I'd like to use this to parse more objects with a similar structure.
Thanks!
Try dozer. You can define mappings from bean to bean using it.
http://dozer.sourceforge.net/
Why you want to parse java object and move data to other java object?
Parsing is for unstructured strings not for objects.
Use setters/getters to move data from one object to the other, using reflection will make you cry when you start doing refactorings.

Serialize Jackson field in two different ways

I am doing POJO serialization / deserialization using Jackson.
Here is a POJO exemple :
public class Pojo {
public String productId;
public String name;
}
I have to read the field productId in this JSON :
{"productId":"1","name":"exemple"}
But also in :
{"_id":"1","name":"exemple"}
To make it short, I would like to use the same object to read the field in a JSON file found somewhere and to save the object as this in MongoDB, using productId as the primary key, which has to be named _id.
Since I am using Jackson (fasterxml) both to read from the file and to write to the database, I can not find a way to do so, except by creating a new class with the same fields (or inheritance) and fill them one by one. Basically, I would like to find a way to put 2 #JsonProperty annotations on productId.
Works with both strings:
public class Pojo {
#JsonProperty("_id")
public String productId;
public String name;
#JsonProperty("productId")
public void setProductId(String id) {
productId = id;
}
}

REST client using both Simple XML and Gson libraries: Use common POJOs or adapter pattern?

In my java app (specifically, Android app), I make a REST call (GET). The response could be either XML or JSON. I use a Strategy Pattern which decides what parser to employ based on the Content Type of the response.
If the response is XML, I use Simple library to parse the response into my POJOs, and if the response is JSON, I use Gson library.
Now my question: Is there any benefit in having a single POJO which containing both Simple and Gson annotations? Or, is it better to separate out the 2 POJOs and then have an Adapter (or maybe Wrapper) to "convert" to a generic POJO? In other words, what are the pros and cons of the following approaches?
Approach 1:
class PojoCommon {
#SimpleXmlAnnotations
#GsonAnnotations
private int age;
#SimpleXmlAnnotations
#GsonAnnotations
private String name;
//Constructors, Getters and Setters ...
}
Approach 2:
class Pojo{
private int age;
private String name;
}
class PojoXml{
#SimpleXmlAnnotations
private int age;
#SimpleXmlAnnotations
private String name;
public Pojo toGenericPojo(){
return new Pojo(this.age, this.name);
}
}
class PojoJson{
#GsonAnnotations
private int age;
#GsonAnnotations
private String name;
public Pojo toGenericPojo(){
return new Pojo(this.age, this.name);
}
}
Though Approach1 is better in term of maintenance but you already have answered your question as in long term with any proposed changes it can make things complex.
My Suggestion is to go for second one create POJO for each individual type and use a wrapper/adapter approach for the conversion

Categories

Resources