Java Jackson writeAsString conversion - java-8

using Java8 with jackson
I have code convert A class into json String, which works fine, i have Scenario where if i want values of rate1 and rate2 to be blank string if certain values.
I am wondering if there is quick and easy way to do it ?
#JsonAutoDetect(fieldVisiblity=ANY)
class A{
UUID id;
CustomEnumType type;
BigDecimal value;
BigDecimal rate1
BigDecimal rate2;
}
A a = new A();
// a filled up with values
string jsonStr = objectMapper.writeValueAsString(a);
I tried using custom Seralizer class as following but not sure how do i convert UUID string representation ?
public class ASerializer extends StdSerializer<A>{
... ASerializer()..
#Override
public void serialize(A value, JsonGenerator g, SerializerProvider p){
g.writeStratObject();
// how do i convert UUID to string ?
g.writeEndObject();
}
}

Just call toString, UUID has static fromString method to deserialize.

Related

Spring boot - Deserialize enum by value lookup

I have the following enum:
public enum BusinessType {
C_CORP("C-Corporation"),
S_CORP("S-Corporation"),
// more types
public final String name;
BusinessType(String name) {
this.name = name;
}
}
The front end will submit the name property as a string (eg. C-Corporation), how can I get spring boot to deserialize / look up the correct enum? Currenty it tries to look up the actual string on the enum, giving the error:
No enum constant ai.interval.common.model.enums.BusinessType.C-Corporation
This is the property I have in the view received from the front end:
BusinessType getBusinessType();
Thanks
Build a getter for your fields, then add the #JsonValue annotation to your getter.
public enum BusinessType {
...
#JsonValue
public String getName() {
return name;
}
}
You can find other options in section 4 of this link: How To Serialize and Deserialize Enums with Jackson

Spring Data MongoDB BeforeSaveCallback not working

I want to have similar functionality as I get with the JPA #PrePersist but in a mongodb database. Reading the spring data mongodb documentation I found the entity callbacks: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#entity-callbacks. They seem to work for what I need so I'm trying to implement some callbacks. I know there are some alternatives for what I'm doing (auditing annotations) but I want to keep with this for the moment.
This is how I register the callback, my entity definition and the repository:
#Configuration
public class BeforeSaveCallbackConfiguration {
#Bean
BeforeSaveCallback<Measurement> beforeSaveMeasurement() {
return (entity, document, collection) -> {
entity.setTimestamp(System.currentTimeMillis());
System.out.println("Before save, timestamp: " + entity.getTimestamp());
return entity;
};
}
}
public interface MeasurementRepository extends MongoRepository<Measurement, String> {
}
#Document
public class Measurement {
private String id;
private long timestamp;
private Float value1;
private Float value2;
// constructor, getters, setters ...
}
I save the entity using measurementRepository.save method of the repository. I actually see the printed line from the callback with the timestamp. However the data saved in the mongodb collection always have timestamp set to 0. Does anyone have any hint?
You implement BeforeConvertCallback interface can work for you:
#Component
public class TestCallBackImpl implements BeforeConvertCallback<Measurement> {
#Override
public Measurement onBeforeConvert(Measurement entity, String collection) {
entity.setTimestamp(System.currentTimeMillis());
return entity;
}
}

Mongotemplate: How to convert result field to custom Java Type?

// collection: test
{
...
Datetime: 43665.384931
...
}
public Class POJO {
#Field("ID")
private String id;
#Field("Datetime")
private Date datetime; // Where can I implement a converter to cast double value from mongo to Java type Date here?
}
mongoTemplate.findOne(new Query(), POJO.class, "test")
Where can I implement a converter to cast double value from mongo to Java type Date here?
You may want to give #Field(targetType = FieldType.INT64) of the upcoming Spring Data MongoDB 2.2 release a try. It allows to pass on type information to the conversion subsystem using the ConversionService to perform the required transformations.
class Pojo {
String id;
#Field(targetType = FieldType.INT64) Date date;
}
At the time of writing there are only converters registered for a Date -> String conversion, but none for Date -> Long, so you'll need to register the converter as well.
((GenericConversionService) mongoTemplate.getConverter().getConversionService())
.addConverter(new Converter<Date, Long>() {
#Override
public Long convert(Date source) {
return source.getTime();
}
});
Registering a MongoCustomConversions bean works for me.

How to parse Dynamic lists with Gson annotations?

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.

Gson Custom deserializer

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

Resources