I do a replication mechanism where I synchronize two databases. For communicating between databases I serialize the objects into JSON using Gson. Each object has a UUID to identify it. To avoid having to send the items that are up to date I use the objects UUID when an object is included in a field in an object to be replicated.
We got the following classes:
public class Entity {
String uuid;
// Getters and setters..
}
public class Article extends Entity {
String name;
Brand brand;
// Getters and setters..
}
public class Brand extens Entity {
String name;
Producer producer
// Getters and setters..
}
public class Producer extends Entity {
String name;
// Getters and setters..
}
If I serialize Article its JSON representation will look like this:
{"brand":"BrandÖ179d7798-aa63-4dd2-8ff6-885534f99e77","uuid":"5dbce9aa-4129-41b6-a8e5-d3c030279e82","name":"Sun-Maid"}
where "BrandÖ179d7798-aa63-4dd2-8ff6-885534f99e77" is the class ("Brand") and the UUID.
If I serialize Brand I expect:
{"producer":"ProducerÖ173d7798-aa63-4dd2-8ff6-885534f84732","uuid":"5dbce9aa-4129-41b6-a8e5-d3c0302w34w2","name":"Carro"}
In Jackson I would change Article class to:
public class Article {
String uuid;
String name;
#JsonDeserialize (using = EntityUUIDDeserializer.class) # JsonSerialize (using = EntityUUIDSerializer.class)
Brand brand;
// Getters and setters..
}
and implement custom serializer and deserializer to return the UUID instead of the object.
Gson do not have a #JsonDeserialize annotation.
If we install the serializer and deserializer doing like this:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Producer.class, new EntityUUIDDeserializer())
.registerTypeAdapter(Brand.class, new EntityUUIDDeserializer())
.registerTypeAdapter/Producer.class, new EntityUUIDSerializer())
.registerTypeAdapter(Brand.class, new EntityUUIDSerializer())
.create();
We can serialize Article and Brand ok.
Deserialize Article by
Article article= gson.fromJson(inputJSONString, Article.class);
works fine but
Brand brand= gson.fromJson(inputJSONString, Brand.class);
do not work. I guess the probem is that when we deserialize a Brand we get the deserializer for Brand to kick in trying to return an UUID string, but we want the deserializer to return a Brand-object instead.
Is there a way to avoid creating two different Gson objects? The problem with two diffrent Gson objects is when you want to deserialize an object that contains both Article and Brand.
You write the serializer/deserializer and register it with Gson (using the GsonBuilder).
https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization
Gson g = new GsonBuilder()
.registerTypeAdapter(Producer.class, new MyProducerDeserializer())
.registerTypeAdapter(Producer.class, new MyProducerSerializer())
.create();
When you serialize/deserialize your Brand class, it will use them for the Producer field contained therein.
Related
I'm using spring data mongo. I have a collection within a document that when I add an item to it I would like to assign a new automatically generated unique identifier to it e.g. (someGeneratedId)
#Document(collection = "questionnaire")
public class Questionnaire {
#Id
private String id;
#Field("answers")
private List<Answer> answers;
}
public class Answer {
private String someGeneratedId;
private String text;
}
I am aware I could use UUID.randomUUID() (wrapped in some kind of service) and set the value, I was just wondering if there was anything out of the box that can handle this? From here #Id seems to be specific to _id field in mongo:
The #Id annotation tells the mapper which property you want to use for
the MongoDB _id property
TIA
No there is no out of the box solution for generating ids for properties on embedded documents.
If you want to keep this away from your business-logic you could implement a BeforeConvertCallback which generates the id's for your embedded objects.
#Component
class BeforeConvertQuestionnaireCallback implements BeforeConvertCallback<Questionnaire> {
#Override
public Questionnaire onBeforeConvert(#NonNull Questionnaire entity, #NonNull String collection) {
for (var answer : entity.getAnswers()) {
if (answer.getId() == null) {
answer.setId(new ObjectId().toString());
}
}
return entity;
}
}
You could also implement this in a more generic manner:
Create a new annotation: #AutogeneratedId.
Then listen to all BeforeConvertCallback's of all entities and iterate through the properties with reflection. Each property annotated with the new annotation gets a unique id if null.
I have two entities: Book and Category and a repository for both. In the controller, I have set up the methods correctly as such:
#RequestMapping(value="/books", method = RequestMethod.GET)
#CrossOrigin
public #ResponseBody List<Book> bookListRest() {
return (List<Book>) bookRepository.findAll();
}
This obviously shows all books and every field in the entity that isn't #JsonIgnore'd. The problem is, I need to have:
One page with Book data (book name, author name, isbn..) without category
One page with Category data (Category name) without books
One page with Everything (book data along with categories where they belong in)
How can one accomplish this?
I somehow need to in a way ignore #jsonignore on some occasions. Should I make a new entity that extends say, Question and also make a repository for that? Surely that can't be the correct way to do this.
As khalid Ahmed Said you can use costum dtos or you can add Filters to ignore specific fields in Jackson. First, we need to define the filter on the java object:
#JsonFilter("myFilterBook")
public class Book{
...
}
#JsonFilter("myFilterCategory")
public class Category{
...
}
Before you return your ResponseBody you try to use ObjectMapper (Jackson):
The case of one page with Book data (book name, author name, isbn..) without category:
ObjectMapper mapper = new ObjectMapper();
SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
.serializeAllExcept("category");
FilterProvider filters = new SimpleFilterProvider()
.addFilter("myFilterBook", theFilter);
String dtoAsString = mapper.writer(filters).writeValueAsString(book);
You can do the same think by putting what you want o ignore for the other example.
And for more details to ignore field during marshalling with jackson you can check here
What about using DTOs data transfer objects
you can create multiple DTOs to use them in the response of your API
DTO is a pojo class that customize the returning data from your entity
public class BookWithoutCategoryDTO {
private String name;
private String authorName;
.....
/// and make setters and getters for them
}
public class BookWithCategoryDTO {
private String name;
private String authorName;
private String category;
.....
/// and make setters and getters for them
}
and create your custom mapper to convert from Book to BookDTO
I've the following domain and needs to return selected field in response to client. How can I achieve that using Spring?
public class Vehicle {
private String vehicleId;
private Long dateCreated;
private String ownerId;
private String colourCode;
private String engineNumber;
private String transmission;
//getters & setters
}
My objective is to return only colourCode and transmission fields to client request. I've read about DTO and seems like I can achieve my objective with DTO but I don't find any good example how to implement it. Is DTO is the correct way to achieve my objective ?
Basically you just create VehicleDTO class with parameters you need
public class VehicleDTO {
private String colourCode;
private String transmission;
//getters and setters
}
and then in your code you construct VehicleDTO from your Vehicle class. Fortunately, we have BeansUtils class from Spring, that uses reflection to copy properties of one object to another, because you do not want to repeat logic for copying properties for every object. So it would be something like:
BeanUtils.copyProperties(v1, dto);
At the end your return VehicleDTO in your response instead of Vehicle
You can return IVehicle interface which exposes your properties of choice
public interface IVehicle {
String getTransmission();
String getColourCode();
}
and your Vehicle implents it
public class Vehicle implements IVehicle{ }
There are various ways you can achieve what you want.
You can add relevant usecase / APi specific DTO for the resource.
e.g. If your API return the vehical general details you may want to expose some level of details,
public class VehicleDetailsDTO {
private String colourCode;
private String transmission;
private String engineNumber; //more
//getters and setters
}
You can then either use BeanUtils or Dozzer to convert your Vehical resource to transportable object like your DTO.
BeanUtils : http://commons.apache.org/proper/commons-beanutils/
Dozzer : http://dozer.sourceforge.net/documentation/mappings.html
Assuming you use JSON as output format and Jackson as serialization engine (default in Spring MVC), you can tell Jackson to not serialize null properties. Now you just need to populate the properties you need and can return the original business object.
I am using Retrofit and Gson to query an API, however I have never come across a JSON response like it.
The Response:
{
Response: {
"Black":[
{"id":"123","code":"RX766"},
{"id":"324","code":"RT344"}],
"Green":[
{"id":"3532","code":"RT983"},
{"id":"242","code":"RL982"}],
"Blue":[
{"id":"453","code":"RY676"},
{"id":"134","code":"R67HJH"}]
}
}
The problem is the list elements id eg "black" is dynamic, so I a have no idea what they will be.
So far I have created a class for the inner type;
class Type {
#SerializedName("id") private String id;
#SerializedName("code") private String code;
}
Is it possible to have the following?
class Response {
#SerializedName("response")
List<Type> types;
}
And then move the list ID into the type, so the Type class would become;
class Type {
#SerializedName("id") private String id;
#SerializedName("code") private String code;
#SerializedName("$") private String type; //not sure how this would be populated
}
If not, how else could this be parsed with just Gson attributes?
Ok so I have just seen this question;
How to parse dynamic JSON fields with GSON?
which looks great, is it possible to wrap a generic map with the response object?
If the keys are dynamic you want a map.
class Response {
#SerializedName("response")
Map<String, List<Type>> types;
}
After deserialization you can coerce the types into something more semantic in your domain.
If this is not suitable you will need to register a TypeAdapter or a JsonDeserializer and do custom deserialization of the map-like data into a simple List.
I want to deserialize json string to java object. My class structure is this
public class Category {
String name;
int id;
ArrayList<Catalog> catalogs;
}
and catalog class structure is this
public class catalog {
private int catalogId = 0;
private String catalogName;
}
Following code i used to deserialize
Gson gson = new Gson();
ArrayList<Category> categories = gson.fromJson(jsonString, Category.class);
I got exception when it try to deserialize ArrayList catalogs;
If i remove ArrayList then it parse successfully
Thanks
Pawan
I solved this problem. The problem is that the string which i am parsing contain boolean value instead of Array . So There is exception while parsing.
The reason is that datatype is not match in json string which is parsed.
Thanks