Java jacksonGeneric Serialization - java

here I have a generic class like :
#JacksonXmlRootElement(localName = "Request")
public class Request<T> {
#JacksonXmlProperty(isAttribute = false,localName="HeaderInfo")
private HeaderInfo headerInfo;
//here I want serialization data use T className
private T data;
}
for example:
I got
Request<User> request; to serialization XML like:
<request><headinfo></headinfo><user></user><request>
Request<SuperUser> request; to serialization XML like:
<request><headinfo></headinfo><SuperUser></SuperUser><request>
ect...

OK I have solve this promblem
code:
public class RequestSerializer extends StdSerializer<Request> {
public RequestSerializer() {
super(Request.class);
}
#Override
public void serialize(Request request, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeObjectField("HeaderInfo", request.getHeaderInfo());
String name = request.getRequest().getClass().getSimpleName();
jgen.writeObjectField(name, request.getRequest());
jgen.writeEndObject();
}
}
JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(true);
module.addSerializer(Request.class, new RequestSerializer());
XmlMapper xml = new XmlMapper(module);

Related

Jackson YAML - serialize null as empty value

I am trying to customise the serialisation of strings to avoid null values in the YAML file.
The code I have so far:
YAMLFactory yamlFactory = new YAMLFactory();
ObjectMapper mapper = new ObjectMapper(yamlFactory);
DefaultSerializerProvider sp = new DefaultSerializerProvider.Impl();
sp.setNullValueSerializer(new NullSerializer());
ObjectMapper m = new ObjectMapper();
mapper.setSerializerProvider(sp);
Map<String, Object> data = new HashMap<>();
data.put("aString", "test");
data.put("aNullObject", null);
data.put("anEmptyString", "");
String output = mapper.writeValueAsString(data);
System.out.println(output);
NullSerializer:
public class NullSerializer extends JsonSerializer<Object> {
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeString("");
}
}
Result:
---
aNullObject: ""
aString: "test"
anEmptyString: ""
The problem is that writeString is writing an empty string, and I'm trying to have an empty value entirely.
Desired result:
---
aNullObject:
aString: "test"
anEmptyString: ""
I tried to use jgen.writeRaw(""); but I get this error:
Caused by: java.lang.UnsupportedOperationException: Operation not supported by generator of type com.fasterxml.jackson.dataformat.yaml.YAMLGenerator
at com.fasterxml.jackson.core.JsonGenerator._reportUnsupportedOperation(JsonGenerator.java:1967)
at com.fasterxml.jackson.dataformat.yaml.YAMLGenerator.writeRaw(YAMLGenerator.java:590)
at com.example.jackson.NullSerializer.serialize(NullSerializer.java:13)
at com.fasterxml.jackson.databind.SerializerProvider.defaultSerializeNull(SerializerProvider.java:1127)
at com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:711)
... 7 more
For me disabling of "MINIMIZE_QUOTES" feature didn't work, still, an empty string is written. The only solution I found was to override ObjectMapper and YamlGenerator and to allow YamlGenerator to write empty raw value. And also you have to provide a custom null serializer that writes this raw value.
class YamlObjectMapper(yamlFactory: YAMLFactory) : ObjectMapper(yamlFactory) {
init {
val dS = DefaultSerializerProvider.Impl()
dS.setNullValueSerializer(NullSerializer)
setSerializerProvider(dS)
}}
class RawYAMLFactory : YAMLFactory() {
override fun _createGenerator(out: Writer?, ctxt: IOContext?): YAMLGenerator? {
val feats = _yamlGeneratorFeatures
return RawYamlGenerator(ctxt, _generatorFeatures, feats, _objectCodec, out, _version)
}}
private object NullSerializer : JsonSerializer<Any?>() {
override fun serialize(value: Any?, jgen: JsonGenerator, provider: SerializerProvider?) {
jgen.writeRaw("")
}}
private class RawYamlGenerator(ctxt: IOContext?, jsonFeatures: Int, yamlFeatures: Int,
codec: ObjectCodec, out: Writer?, version: DumperOptions.Version?)
: YAMLGenerator(ctxt, jsonFeatures, yamlFeatures, codec, out, version) {
override fun writeRaw(c: String) {
_writeContext.writeValue()
_emit(_scalarEvent("", DumperOptions.ScalarStyle.PLAIN))
}}
Based on the #Yuliia Liubchyk solution - I rewrote his code into Java.
Instance:
var yamlObjectMapper = new YamlObjectMapper(new RawYamlFactory().
enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)).
findAndRegisterModules();
class NullValueSerializer extends JsonSerializer<Object> {
#Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeRaw("");
}
}
public class RawYamlFactory extends YAMLFactory {
#Override
protected YAMLGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException {
var feats = _yamlGeneratorFeatures;
return new RawYamlGenerator(ctxt, _generatorFeatures, feats, _objectCodec, out, _version);
}
}
public class RawYamlGenerator extends YAMLGenerator {
public RawYamlGenerator(IOContext ctxt, int jsonFeatures, int yamlFeatures,
ObjectCodec codec, Writer out, DumperOptions.Version version) throws IOException {
super(ctxt, jsonFeatures, yamlFeatures, codec, out, version);
}
#Override
public void writeRaw(String text) throws IOException {
_writeContext.writeValue();
_emit(_scalarEvent("", DumperOptions.ScalarStyle.PLAIN));
}
}
public class YamlObjectMapper extends ObjectMapper {
public YamlObjectMapper(YAMLFactory jf) {
super(jf);
final DefaultSerializerProvider.Impl ds = new DefaultSerializerProvider.Impl();
ds.setNullValueSerializer(new NullValueSerializer());
setSerializerProvider(ds);
}
}
I had a similar problem but using an enum (or object) and not a string directly you can implement a serializer and decide to add or remove the """ before to serialize the information.
For example
public class Data {
private String aString;
private MyData aNullObject;
private String anEmptyString;
...
}
public class MyData {
private String value;
....
}
public class MySerializer {
#Override
public void serialize(
MyData data, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
YAMLGenerator yamlGenerator = (YAMLGenerator) jgen;
//DISABLE QUOTES
yamlGenerator.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
yamlGenerator.writeString(data.getValue());
//ENABLE QUOTES AGAIN
yamlGenerator.disable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
}
}
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
SimpleModule module = new SimpleModule();
module.addSerializer(MyData.class, new MySerializer());
mapper.registerModule(module);
I hope to explain correctly...

Rewriting ArrayList XML serialisation with jackson-dataformat-xml

If I use jackson-dataformat-xml to serialise an ArrayList of JsonNode it produces the following:
<ArrayList><item>...</item><item>...</item></ArrayList>
I'd like to have it read:
<events><event>...</event><event>...</event></events>
I've tried using a custom serialiser and does give me the <event/> tags I want but it also still wraps everything in an <ArrayList><item></item></ArrayList>
public class ArrayListSerializer extends JsonSerializer<ArrayList<JsonNode>> {
#Override
public void serialize(ArrayList<JsonNode> value, JsonGenerator gen,
SerializerProvider serializers)
throws IOException, JsonProcessingException {
gen.writeStartObject();
for (JsonNode node : value) {
gen.writeObjectField("event", node);
}
gen.writeEndObject();
}
#Override
public Class<ArrayList<JsonNode>> handledType() {
#SuppressWarnings("unchecked")
Class<ArrayList<JsonNode>> typeClass = (Class<ArrayList<JsonNode>>)(Class<?>)List.class;
return typeClass;
}
}
Any suggestions? Thanks.
You can also consider defining the XML element names using annotations. Here is an example:
public class JacksonXmlArray {
static class Document {
#JsonProperty
#JacksonXmlElementWrapper(localName = "events")
#JacksonXmlProperty(localName = "event")
List<String> events = Arrays.asList("a", "b");
}
public static void main(String[] args) throws JsonProcessingException {
final XmlMapper xmlMapper = new XmlMapper();
System.out.println(xmlMapper.writeValueAsString(new Document()));
}
}
Output:
<Document xmlns=""><events><event>a</event><event>b</event></events></Document>

Customize JSON serialization with JaxRS

In a webservice call, I would like to return my objects with this JSON structure.
{
"date" : "30/06/2014",
"price" : {
"val" : "12.50",
"curr" : "EUR"
}
}
I'd like to map this JSON code to this Java structure (with joda-time and joda-money):
public class MyResponse {
LocalDate date;
Money price;
}
My webservice currently looks like this:
#javax.ws.rs.POST
#javax.ws.rs.Path("test")
#javax.ws.rs.Produces({MediaType.APPLICATION_JSON})
#javax.ws.rs.Consumes({MediaType.APPLICATION_JSON})
public MyResponse test(MyRequest request) {
MyResponse response = new MyResponse();
response.setDate(LocalDate.now());
response.setMoney(Money.parse("EUR 12.50"));
return response;
}
So my question is: where do I register a custom handler to format dates as I want as well as money representations?
If you are using Jackson (which should be the default for JBoss EAP 6) you can use custom JsonSerializers
For the LocalDate:
public class DateSerializer extends JsonSerializer<LocalDate> {
#Override
public void serialize(LocalDate date, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(date.toString("dd/MM/yyyy"));
}
}
For the Money:
public class MoneySerializer extends JsonSerializer<Money> {
#Override
public void serialize(Money money, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeStringField("val", money.getAmount().toString());
jgen.writeStringField("curr", money.getCurrencyUnit().getCurrencyCode());
jgen.writeEndObject();
}
}
Both Serializers can be registered globally:
#Provider
public class JacksonConfig implements ContextResolver<ObjectMapper> {
private ObjectMapper objectMapper;
public JacksonConfig() {
objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null));
module.addSerializer(Money.class, new MoneySerializer());
module.addSerializer(LocalDate.class, new DateSerializer());
objectMapper.registerModule(module);
}
public ObjectMapper getContext(Class<?> objectType) {
return objectMapper;
}
}
For parsing JSON in this custom format you need to implement custom JsonDeserializers.
If you are using Jettison you can do the same thing with custom XmlAdapters.

How do I use a custom Serializer with Jackson?

I have two Java classes that I want to serialize to JSON using Jackson:
public class User {
public final int id;
public final String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Item {
public final int id;
public final String itemNr;
public final User createdBy;
public Item(int id, String itemNr, User createdBy) {
this.id = id;
this.itemNr = itemNr;
this.createdBy = createdBy;
}
}
I want to serialize an Item to this JSON:
{"id":7, "itemNr":"TEST", "createdBy":3}
with User serialized to only include the id. I will also be able to serilize all user objects to JSON like:
{"id":3, "name": "Jonas", "email": "jonas#example.com"}
So I guess that I need to write a custom serializer for Item and tried with this:
public class ItemSerializer extends JsonSerializer<Item> {
#Override
public void serialize(Item value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeNumberField("itemNr", value.itemNr);
jgen.writeNumberField("createdBy", value.user.id);
jgen.writeEndObject();
}
}
I serialize the JSON with this code from Jackson How-to: Custom Serializers:
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule",
new Version(1,0,0,null));
simpleModule.addSerializer(new ItemSerializer());
mapper.registerModule(simpleModule);
StringWriter writer = new StringWriter();
try {
mapper.writeValue(writer, myItem);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But I get this error:
Exception in thread "main" java.lang.IllegalArgumentException: JsonSerializer of type com.example.ItemSerializer does not define valid handledType() (use alternative registration method?)
at org.codehaus.jackson.map.module.SimpleSerializers.addSerializer(SimpleSerializers.java:62)
at org.codehaus.jackson.map.module.SimpleModule.addSerializer(SimpleModule.java:54)
at com.example.JsonTest.main(JsonTest.java:54)
How can I use a custom Serializer with Jackson?
This is how I would do it with Gson:
public class UserAdapter implements JsonSerializer<User> {
#Override
public JsonElement serialize(User src, java.lang.reflect.Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.id);
}
}
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(User.class, new UserAdapter());
Gson gson = builder.create();
String json = gson.toJson(myItem);
System.out.println("JSON: "+json);
But I need to do it with Jackson now, since Gson doesn't have support for interfaces.
You can put #JsonSerialize(using = CustomDateSerializer.class) over any date field of object to be serialized.
public class CustomDateSerializer extends SerializerBase<Date> {
public CustomDateSerializer() {
super(Date.class, true);
}
#Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)");
String format = formatter.format(value);
jgen.writeString(format);
}
}
As mentioned, #JsonValue is a good way. But if you don't mind a custom serializer, there's no need to write one for Item but rather one for User -- if so, it'd be as simple as:
public void serialize(Item value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeNumber(id);
}
Yet another possibility is to implement JsonSerializable, in which case no registration is needed.
As to error; that is weird -- you probably want to upgrade to a later version. But it is also safer to extend org.codehaus.jackson.map.ser.SerializerBase as it will have standard implementations of non-essential methods (i.e. everything but actual serialization call).
I tried doing this too, and there is a mistake in the example code on the Jackson web page that fails to include the type (.class) in the call to addSerializer() method, which should read like this:
simpleModule.addSerializer(Item.class, new ItemSerializer());
In other words, these are the lines that instantiate the simpleModule and add the serializer (with the prior incorrect line commented out):
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule",
new Version(1,0,0,null));
// simpleModule.addSerializer(new ItemSerializer());
simpleModule.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(simpleModule);
FYI: Here is the reference for the correct example code: http://wiki.fasterxml.com/JacksonFeatureModules
Use #JsonValue:
public class User {
int id;
String name;
#JsonValue
public int getId() {
return id;
}
}
#JsonValue only works on methods so you must add the getId method.
You should be able to skip your custom serializer altogether.
I wrote an example for a custom Timestamp.class serialization/deserialization, but you could use it for what ever you want.
When creating the object mapper do something like this:
public class JsonUtils {
public static ObjectMapper objectMapper = null;
static {
objectMapper = new ObjectMapper();
SimpleModule s = new SimpleModule();
s.addSerializer(Timestamp.class, new TimestampSerializerTypeHandler());
s.addDeserializer(Timestamp.class, new TimestampDeserializerTypeHandler());
objectMapper.registerModule(s);
};
}
for example in java ee you could initialize it with this:
import java.time.LocalDateTime;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
#Provider
public class JacksonConfig implements ContextResolver<ObjectMapper> {
private final ObjectMapper objectMapper;
public JacksonConfig() {
objectMapper = new ObjectMapper();
SimpleModule s = new SimpleModule();
s.addSerializer(Timestamp.class, new TimestampSerializerTypeHandler());
s.addDeserializer(Timestamp.class, new TimestampDeserializerTypeHandler());
objectMapper.registerModule(s);
};
#Override
public ObjectMapper getContext(Class<?> type) {
return objectMapper;
}
}
where the serializer should be something like this:
import java.io.IOException;
import java.sql.Timestamp;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class TimestampSerializerTypeHandler extends JsonSerializer<Timestamp> {
#Override
public void serialize(Timestamp value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
String stringValue = value.toString();
if(stringValue != null && !stringValue.isEmpty() && !stringValue.equals("null")) {
jgen.writeString(stringValue);
} else {
jgen.writeNull();
}
}
#Override
public Class<Timestamp> handledType() {
return Timestamp.class;
}
}
and deserializer something like this:
import java.io.IOException;
import java.sql.Timestamp;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class TimestampDeserializerTypeHandler extends JsonDeserializer<Timestamp> {
#Override
public Timestamp deserialize(JsonParser jp, DeserializationContext ds) throws IOException, JsonProcessingException {
SqlTimestampConverter s = new SqlTimestampConverter();
String value = jp.getValueAsString();
if(value != null && !value.isEmpty() && !value.equals("null"))
return (Timestamp) s.convert(Timestamp.class, value);
return null;
}
#Override
public Class<Timestamp> handledType() {
return Timestamp.class;
}
}
These are behavior patterns I have noticed while trying to understand Jackson serialization.
1) Assume there is an object Classroom and a class Student. I've made everything public and final for ease.
public class Classroom {
public final double double1 = 1234.5678;
public final Double Double1 = 91011.1213;
public final Student student1 = new Student();
}
public class Student {
public final double double2 = 1920.2122;
public final Double Double2 = 2324.2526;
}
2) Assume that these are the serializers we use for serializing the objects into JSON. The writeObjectField uses the object's own serializer if it is registered with the object mapper; if not, then it serializes it as a POJO. The writeNumberField exclusively only accepts primitives as arguments.
public class ClassroomSerializer extends StdSerializer<Classroom> {
public ClassroomSerializer(Class<Classroom> t) {
super(t);
}
#Override
public void serialize(Classroom value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
jgen.writeStartObject();
jgen.writeObjectField("double1-Object", value.double1);
jgen.writeNumberField("double1-Number", value.double1);
jgen.writeObjectField("Double1-Object", value.Double1);
jgen.writeNumberField("Double1-Number", value.Double1);
jgen.writeObjectField("student1", value.student1);
jgen.writeEndObject();
}
}
public class StudentSerializer extends StdSerializer<Student> {
public StudentSerializer(Class<Student> t) {
super(t);
}
#Override
public void serialize(Student value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
jgen.writeStartObject();
jgen.writeObjectField("double2-Object", value.double2);
jgen.writeNumberField("double2-Number", value.double2);
jgen.writeObjectField("Double2-Object", value.Double2);
jgen.writeNumberField("Double2-Number", value.Double2);
jgen.writeEndObject();
}
}
3) Register only a DoubleSerializer with DecimalFormat output pattern ###,##0.000, in SimpleModule and the output is:
{
"double1" : 1234.5678,
"Double1" : {
"value" : "91,011.121"
},
"student1" : {
"double2" : 1920.2122,
"Double2" : {
"value" : "2,324.253"
}
}
}
You can see that the POJO serialization differentiates between double and Double, using the DoubleSerialzer for Doubles and using a regular String format for doubles.
4) Register DoubleSerializer and ClassroomSerializer, without the StudentSerializer. We expect that the output is such that if we write a double as an object, it behaves like a Double, and if we write a Double as a number, it behaves like a double. The Student instance variable should be written as a POJO and follow the pattern above since it does not register.
{
"double1-Object" : {
"value" : "1,234.568"
},
"double1-Number" : 1234.5678,
"Double1-Object" : {
"value" : "91,011.121"
},
"Double1-Number" : 91011.1213,
"student1" : {
"double2" : 1920.2122,
"Double2" : {
"value" : "2,324.253"
}
}
}
5) Register all serializers. The output is:
{
"double1-Object" : {
"value" : "1,234.568"
},
"double1-Number" : 1234.5678,
"Double1-Object" : {
"value" : "91,011.121"
},
"Double1-Number" : 91011.1213,
"student1" : {
"double2-Object" : {
"value" : "1,920.212"
},
"double2-Number" : 1920.2122,
"Double2-Object" : {
"value" : "2,324.253"
},
"Double2-Number" : 2324.2526
}
}
exactly as expected.
Another important note: If you have multiple serializers for the same class registered with the same Module, then the Module will select the serializer for that class that is most recently added to the list. This should not be used - it's confusing and I am not sure how consistent this is
Moral: if you want to customize serialization of primitives in your object, you must write your own serializer for the object. You cannot rely on the POJO Jackson serialization.
Jackson's JSON Views might be a simpler way of achieving your requirements, especially if you have some flexibility in your JSON format.
If {"id":7, "itemNr":"TEST", "createdBy":{id:3}} is an acceptable representation then this will be very easy to achieve with very little code.
You would just annotate the name field of User as being part of a view, and specify a different view in your serialisation request (the un-annotated fields would be included by default)
For example:
Define the views:
public class Views {
public static class BasicView{}
public static class CompleteUserView{}
}
Annotate the User:
public class User {
public final int id;
#JsonView(Views.CompleteUserView.class)
public final String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
And serialise requesting a view which doesn't contain the field you want to hide (non-annotated fields are serialised by default):
objectMapper.getSerializationConfig().withView(Views.BasicView.class);
In my case (Spring 3.2.4 and Jackson 2.3.1), XML configuration for custom serializer:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="serializers">
<array>
<bean class="com.example.business.serializer.json.CustomObjectSerializer"/>
</array>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
was in unexplained way overwritten back to default by something.
This worked for me:
CustomObject.java
#JsonSerialize(using = CustomObjectSerializer.class)
public class CustomObject {
private Long value;
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
}
CustomObjectSerializer.java
public class CustomObjectSerializer extends JsonSerializer<CustomObject> {
#Override
public void serialize(CustomObject value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("y", value.getValue());
jgen.writeEndObject();
}
#Override
public Class<CustomObject> handledType() {
return CustomObject.class;
}
}
No XML configuration (<mvc:message-converters>(...)</mvc:message-converters>) is needed in my solution.
The problem in your case is the ItemSerializer is missing the method handledType() which needs to be overridden from JsonSerializer
public class ItemSerializer extends JsonSerializer<Item> {
#Override
public void serialize(Item value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeNumberField("itemNr", value.itemNr);
jgen.writeNumberField("createdBy", value.user.id);
jgen.writeEndObject();
}
#Override
public Class<Item> handledType()
{
return Item.class;
}
}
Hence you are getting the explicit error that handledType() is not defined
Exception in thread "main" java.lang.IllegalArgumentException: JsonSerializer of type com.example.ItemSerializer does not define valid handledType()
Hope it helps someone. Thanks for reading my answer.
If your only requirement in your custom serializer is to skip serializing the name field of User, mark it as transient. Jackson will not serialize or deserialize transient fields.
[ see also: Why does Java have transient fields? ]
You have to override method handledType and everything will work
#Override
public Class<Item> handledType()
{
return Item.class;
}

how to create a custom JsonDeserializer in Java?

I have a Map<A,B> fieldOfC as a field of a class C. When I try to deserialize C with Jackson, an Exception is thrown because it can't find a Deserializer for Map's key A. So, I guess the solution is to extend StdJsonDeserializer and do it manually.
My problem is that I can't find an example on how to use the parser and the context of the method "deserialize" that I have to implement.
Can anyone write the code for this simple example so I can use it as a start to build my real deserializer?
public class A{
private String a1;
private Integer a2;
}
public class B{
private String b1;
}
public class C{
#JsonDeserialize(keyUsing=ADeserializer.class)
//also tried this: #JsonDeserialize(keyAs=A.class) without success
private Map<A,B> fieldOfC;
private String c1;
}
public class ADeserializer extends StdKeyDeserializer {
protected ADeserializer(Class<A> cls) {
super(cls);
}
protected Object _parse(String key, DeserializationContext ctxt) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(key, A.class);
}
}
Thanks in advance
EDIT: googling, I found a test of the same problem I have. This is exactly my problem
EDIT: changed extended class from StdDeserializer to StdKeyDeserializer as I read here in method findKeyDeserializer(org.codehaus.jackson.map.DeserializationConfig, org.codehaus.jackson.type.JavaType, org.codehaus.jackson.map.BeanProperty)
EDIT: After solving this issue I got this one that is related.
I am a complete newbie with Jackson, but the following works for me.
First I add a JsonCreator method to A:
public class A {
private String a1;
private Integer a2;
public String getA1() { return a1; }
public Integer getA2() { return a2; }
public void setA1(String a1) { this.a1 = a1; }
public void setA2(Integer a2) { this.a2 = a2; }
#JsonCreator
public static A fromJSON(String val) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
A a = mapper.readValue(val,A.class);
return a;
}
}
That alone solves the deserialization problem. The harder part for me was the correct serialization of the keys. What I did there was to define a key serializer that serializes named classes as there JSON serialization, like this:
public class KeySerializer extends SerializerBase<Object> {
private static final SerializerBase<Object> DEFAULT = new StdKeySerializer();
private Set<Class<?>> objectKeys_ = Collections.synchronizedSet(new HashSet<Class<?>>());
protected KeySerializer(Class<?>... objectKeys) {
super(Object.class);
for(Class<?> cl:objectKeys) {
objectKeys_.add(cl);
}
}
#Override
public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException {
return DEFAULT.getSchema(provider, typeHint);
}
#Override
public void serialize(Object value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonGenerationException {
if (objectKeys_.contains(value.getClass())) {
ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
mapper.writeValue(writer, value);
jgen.writeFieldName(writer.toString());
} else {
DEFAULT.serialize(value, jgen, provider);
}
}
}
Then to prove it works, serializing and deserializing an instance of class C:
ObjectMapper mapper = new ObjectMapper();
StdSerializerProvider provider = new StdSerializerProvider();
provider.setKeySerializer(new KeySerializer(A.class));
mapper.setSerializerProvider(provider);
StringWriter out = new StringWriter();
mapper.writeValue(out, c);
String json = out.toString();
System.out.println("JSON= "+json);
C c2 = mapper.readValue(json, C.class);
System.out.print("C2= ");
StringWriter outC2 = new StringWriter();
mapper.writeValue(outC2, c2);
System.out.println(outC2.toString());
For me this produced the output:
JSON= {"c1":"goo","map":{"{\"a1\":\"1ccf\",\"a2\":7376}":{"b1":"5ox"},"{\"a1\":\"1cd2\",\"a2\":7379}":{"b1":"5p0"},"{\"a1\":\"1cd5\",\"a2\":7382}":{"b1":"5p3"},"{\"a1\":\"1cd8\",\"a2\":7385}":{"b1":"5p6"}}}
C2= {"c1":"goo","map":{"{\"a1\":\"1ccf\",\"a2\":7376}":{"b1":"5ox"},"{\"a1\":\"1cd2\",\"a2\":7379}":{"b1":"5p0"},"{\"a1\":\"1cd5\",\"a2\":7382}":{"b1":"5p3"},"{\"a1\":\"1cd8\",\"a2\":7385}":{"b1":"5p6"}}}
I feel there ought to have been a better way of doing saying how to serialize the key by using annotations, but I could not work it out.

Categories