I'm trying to use a custom deserializer in Jackson to deserialize some json objects. However, when I try to have the ObjectMapper read the json, the following exception occurs:
java.lang.IllegalStateException: AnnotationIntrospector returned Class com.Geometry.GeometryDeserializer; expected Class<JsonDeserializer>
I'm somewhat at a loss of what to do here, since it seems like the AnnotationIntrospector is complaining that my GeometryDeserializer is not a subclass of JsonDeserializer, when it clearly is.
Here's where I create the Object Mapper:
public void deserializeJson(String json) {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Feature.class, MixIn.class);
Feature feature = mapper.readValue(json, Feature.class);
}
...my Mix In class:
abstract class MixIn {
#JsonDeserialize(using=GeometryDeserializer.class)
abstract void setGeometry(Geometry geometry);
}
...and my deserializer:
public class GeometryDeserializer extends JsonDeserializer<Geometry> {
#Override
public Geometry deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
//stuff happens
}
}
Any feedback/assistance would be greatly appriciated.
Thanks.
Wild guess: you are accidentally mixing up Jackson 1.x and Jackson 2.x types? Class names are mostly the same, but live in different packages -- things work when using one set of classes, but IDEs may cause accidental mix-ups.
Related
In jackson, we can uses the annotations
#JsonTypeInfo
#JsonSubTypes
#JsonSubTypes.Type
to implement polymorphic serialization.
We can choose to
Use these annotations on data model directly, this is the simplest way.
Use these annotations on mixin. Here is a link about it Polymorphic deserialization in Jackson without annotations.
Both of these two solutions have a problem: All the sub classes must be known when writing code.
In GraphQL
The discriminator field is fixed: "__typename"
The sub type names are fixed too: Simple name of java classes
All the requirements are fixed, that means it unnecessary to configure sub types one by one, it's possible to create a jackson module to handle them automatically.
// An empty interface
// Developers need not to configure polymorphic metadata for any class of its subtypes
public interface GraphQLObject {}
public class BookStore implements GraphQLObject {
public List<Book> getBooks() {...}
...other gettes/setters...
}
public abstract class Book implements GraphQLObject {
... some properties ...
}
public class ElectronicBook extends Book {
... some properties ...
}
public class PaperBook extends Book {
... some properties ...
}
The usage code looks like this
BookStore store = ...;
ObjectMapper mapper = new ObjectMapper();
mapper.addModule(new GraphQLModule());
System.out.println(mapper.writeValueAsString(store));
Here, we need to create "GraphQLModule", it can handle all the sub types implement the empty interface "GraphQLObject", and tell jackson how to use the simple class name of each subtype to be the value of discriminator field "__typename"
The result should looks like:
{
name: "store",
books: [
{ __typename: "ElectronicBook", name: "book-1" },
{ __typename: "PaperBook", name: "book-2" }
]
}
Is it possible to implement the "GraphQLModule"?
Note:
Like the default polymorphic behavior of jackson, discriminator field only need to be added when the object runtime type is different with the generic type argument of list which is known when compile.
I found the reason.
I try to defined customer serializer, but I found "serializeWithType" is never called.
In my project, data type is interface. I use ASM to generate its bytecode. I only generated the simplest bytecode and ignored the signature for generic.
So, in the inteface, it's List<Book>
But, in my bytecode implementation, it's List
It is possible to implement the "GraphQLModule" module extending the SimpleModule class:
public class GraphQLModule extends SimpleModule {
public GraphQLModule() {
this.addSerializer(new GraphQLSerializer());
}
}
I added inside the module a new serializer that extends the StdSerializer class:
public class GraphQLSerializer extends StdSerializer<GraphQLObject> {
public GraphQLSerializer() {
super(GraphQLObject.class);
}
#Override
public void serialize(GraphQLObject obj, JsonGenerator jg, SerializerProvider sp) throws IOException {
jg.writeStartObject();
jg.writeStringField("__typename", obj.getClass().getSimpleName());
jg.writeEndObject();
}
}
The GraphQLSerializer serializer simply takes your object implementing your GraphQLObject interface and serialize it including in the json just the classname string of the object as a __typename.
So you can add register this module to your objectMapper and use it like in this example :
public interface GraphQLObject {}
public abstract class Book implements GraphQLObject {}
public class ElectronicBook extends Book {}
public class PaperBook extends Book {}
ObjectMapper objectMapper = new ObjectMapper();
mapper.registerModule(new GraphQLModule());
List<Book> books = List.of(new ElectronicBook(), new PaperBook());
//it will print [{"__typename":"ElectronicBook"},{"__typename":"PaperBook"}]
System.out.println(mapper.writeValueAsString(books));
I meet an issue with a class contained in a library that I use.
This issue comes when I want deserialize it.
Indeed, this class has a method names "getCopy" which returns a new instance of himself which contains this same method and call it still a StackOverFlowException on the following cycle :
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:166)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:723)
public class Object {
...
ObjectAttribute objectAttribute;
...
public ObjectAttribute getObjectAttribute(){
return this.objectAttribute
}
...
}
public class ObjectAttribute{
...
public ObjectAttribute getCopy{
return copy(this) //return a new instance of himself
}
...
}
Is there a way to ignore the method getCopy() like #JsonIgnoreAttribute("objectProperty.copy")?
For this specific use case, when you have a class in a third party library that you are not able to modify, Jackson provides the Mix-in annotations.
The idea behind this concept is to provide a class that indicates how the serialization of another class should be accomplished.
For instance, consider the following mix-in class definition for your use case:
public abstract class ObjectAttributeMixIn{
// You need to provide definitions for every property you need
// to serialize, and the proper constructor if necessary
...
// Ignore the getCopy method
#JsonIgnore
public abstract ObjectAttribute getCopy();
...
}
You can use the full set of Jackson annotations in the mix-in definitions.
Then, associate the mix-in with the ObjectAttribute class. You can use the instance of ObjectMapper you are using for serialization for this purpose:
objectMapper.addMixInAnnotations(ObjectAttribute.class, ObjectAttributeMixIn.class);
Yon can also register a custom module instead; please, see the relevant documentation.
for ignore method getCopy, just enough rename this method , e.g copy
every method start with get then serialized ,e.g if method name is getSomething then serialized to something: (return value by method))
so if you change method name to copy or copyInstance or every name without start by get then method not serialized
You can override JsonSerializer and do specific logic for class
public class CustomSerializerForC extends JsonSerializer<C> {
#Override
public Class<C> handledType() {
return C.class;
}
#Override
public void serialize(C c, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
String upperCase = c.getValue().toUpperCase();
jsonGenerator.writeString(upperCase);
}
}
And use Serializer in moudle used in ObjectMapper:
SimpleModule module = new SimpleModule("MyCustomModule", new Version(1, 0, 0, null));
module.addSerializer(new CustomSerializerForC());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
There are 2 ways I see how to figure out your issue:
Write custom deserializer for you specific class and register it in Jackson mapper.
Tune up global Jackson mapper to ignore class getters in auto-detection and use only fields.
Please try 2 way with following config:
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(JsonMethod.ALL, Visibility.NONE);
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
If you decide to move forward with 1 way, please write here if you need help.
You can register serializer and choose the fields you would like
/**
* We can not change source code so we are adding serializer for a specific type.
*
*/
public static class JsonSpecificTypeSerializer extends JsonSerializer<SpecificType> {
#Override
public void serialize(SpecificType t, JsonGenerator jsonGen, SerializerProvider serializerProvider) throws IOException {
jsonGen.writeStartObject();
jsonGen.writeFieldName("field1");
jsonGen.writeNumber(t.getield1());
.......
jsonGen.writeEndObject();
}
}
/**
* Customize jackson.
*
* adding configuration to jackson without overriding spring boot default conf.
*/
#Bean
public Jackson2ObjectMapperBuilderCustomizer customizeJackson() {
return jacksonObjectMapperBuilder -> {
jacksonObjectMapperBuilder.serializerByType(SpecificType.class,
new JsonSpecificTypeSerializer());
};
}
I have a method in a class called "HttpResponseHelper" that I am trying to Unit Test when it throws a JsonProcessingException, but I was having difficulties getting it do so:
private static void populateHTTPResponseWithData(ObjectNode httpResponse)
{
ObjectMapper mapper = new ObjectMapper();
responseMapData.keySet().forEach(item -> {
try
{
httpResponse.put(item, mapper.writeValueAsString(responseMapData.get(item)));
}
catch (JsonProcessingException e)
{
LOGGER.error("Json Processing Exception", e);
}
});
}
The httpResponse argument is type ObjectNode (Jackson library), and then inside the method body a mapper object is created from the ObjectMapper class.
The resonseMapData is a ConcurrentHashMap> from a class called "MessageProcessResults". It looks like here its looping through the keySet and inserting a String for the Key Value pair inside of the httpResponse argument.
I tried using mockito on mapper to return a malformed JSON, but it looks like it writes the value as a String and passes each time.
Does anyone have any suggestions or is there a simple way to do this? Thank you for taking the time to read this question and possibly help me :D
You can also extend JsonProcessingException for your tests:
private static class MockJsonProcessingException extends JsonProcessingException {
public MockJsonProcessingException(String message) {
super(message);
}
}
And then in your test:
var exception = new MockJsonProcessingException("Because of protected constructors");
when(objectMapper.writeValueAsString(thing)).thenThrow(exception);
EDIT: Note this assumes you're using dependency injection and injecting a mock ObjectMapper into your object, as is necessary to make this case testable.
The #HarryQ answer wont work as JsonProcessingException has a package protected constructor.
For those methods that throw this you can use InputCoercionException. It extends from JsonProcesssingException and allows something like, ugly, yeah I know, but it works:
when(mockObjectMapper.writeValueAsString(any())).thenThrow(new InputCoercionException(null, "my mock exception", null, null));
When you are doing unit test, you don't focus on how the underlying code would create an exception, but how your code deal with such an exception. In that regards, you can mock the ObjectNode object, and ask it to throw an exception whenever put method is called.
#Test
public void someTest(){
Object mockObject = Mockito.mock(ObjectNode.class);
Mockito.when(mockObject.put()).thenThrow(new JsonProcessingException ("my mock exception"));
functionUndertest(mockObject); //this is where you inject your mock function. In your case you are expecting a error message to be printed.
}
I am trying to generically print any object with mapper.writeValueAsString but I am facing a infinite recursion when deserializing objects with Mockito and Jackson. The objects I am trying to deserialize perform underlying Hibernate calls to DBs etc and I have no control over the classes themselves.
Currently I am using the following versions of Mockito and Jackson but the same is happening for older 1.X versions of Jackson.
Mockito: org.mockito:mockito-all:jar:1.9.5:compile
Jackson: com.fasterxml.jackson.core:jackson-databind:jar:2.9.7:compile
As specified, I cannot modify the underlying classes with annotation such as #JsonIgnore because they are outside dependencies not under my control. I also cannot create mixins for my user case because I am trying to generically print the contents of any object that is sent in.
I have tried adding the DeserializationConfig FAIL_ON_UNKNOWN_PROPERTIES to false in older Jackson version and I have tried setting the DeserializationFeature FAIL_ON_MISSING_CREATOR_PROPERTIES to false.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public static PrintUtil {
public static String printJSON(Object obj) {
String printstring = "printfailed";
try {
ObjectMapper mapper = new ObjectMapper();
LOG.debug("formatted JSON String ");
printstring = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return printstring;
}
}
The infinite recursion terminal output is seen when running Mockito tests for methods that contain Log4j statements which in turn call the PrintUtil function. The statement e.printStackTrace() begins printing while running the tests.
Most of the object that are being sent to this utility method are JAXB XML Service Response Objects.
Without being able to modify the classes themselves, I see two possible solutions.
1) Wrap the objects into objects you own as suggested by #TheHeadRush and annotate it appropriately. I would suggest using #JsonIdentityInfo so the objects serialize to their ID, rather than being ignored completely with #JsonIgnore.
2) Use a custom deserializer for the object which is causing the recursion. Here is an example:
public class CustomDeserializer extends StdDeserializer<MyObject>{
// Add constructors as necessary.
#Override
public List<Item> deserialize(
JsonParser jsonparser,
DeserializationContext context)
throws IOException, JsonProcessingException {
return null; // Return something that won't recurse here.
}
}
Then register the deserializer with the ObjectMapper you are using:
// Register the deserializer:
SimpleModule module = new SimpleModule()
.addDeserializer(MyObject.class, new CustomDeserializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
I want to hook into Jackson's deserialization to optionally deserialize a different JSON document than the one provided. That seems like a really weird use case so let me explain.
I am using the Amazon SQS Extended client to put messages that are too large for SQS on S3 instead and a message that looks like this through SQS
["com.amazon.sqs.javamessaging.MessageS3Pointer",{"s3BucketName":"my-bucket","s3Key":"f5a0fa29-7f9c-4852-8bbb-53697799efe2"}]
An elastic beanstalk worker is listening to the other end of that which means that those messages are POSTed to a Jersey endpoint my application maintains. Since those messages are POSTed instead of using a SQS receiveMessage call the extended client will not fetch the message from S3 itself.
I was thinking it would be pretty clever to make a custom JsonDeserializer that would look at the message to see if it was an S3 pointer, download that file, and deserialize it. Otherwise, just deserialize the provided message. However, that isn't working out quite as smoothly as I hoped.
Here is what I have so far:
public class SQSS3Deserializer<T> extends JsonDeserializer<T> {
private static final String s3PointerHeader = "com.amazon.sqs.javamessaging.MessageS3Pointer";
private Class<T> type;
private ObjectMapper mapper = new ObjectMapper();
public SQSS3Deserializer() {
super();
type = getParameterizedTypeArgument();
}
#Override
public T deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
if (jp.isExpectedStartArrayToken()) {
jp.nextToken();
if (s3PointerHeader.equals(jp.getValueAsString())) {
jp.nextToken();
S3Pointer p = jp.readValueAs(S3Pointer.class);
return mapper.readValue(S3Utils.getInputStream(p.s3BucketName, p.s3Key), type);
}
}
return jp.readValueAs(type);
}
#SuppressWarnings("unchecked")
protected Class<T> getParameterizedTypeArgument() {
return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
static private class S3Pointer {
public String s3BucketName;
public String s3Key;
}
}
For each POJO I want to deserialize I'll have to create an empty subclass with the correct generic specialization, for example:
public class POJOS3Deserializer extends SQSS3Deserializer<POJO> {}
I also will need to add the JsonDeserializer annotation to the class
#JsonDeserialize(using=POJOS3Deserializer.class)
public class POJO { ... }
However, doing it this way causes a stack overflow error because it will continually reenter my deserializer when it calls JsonParser.readValueAs() since readValueAs looks at the JsonDeserialize annotation.
So, I have two questions:
How do I change this to keep this fairly generic and still have Jackson do most of the heavy lifting of parsing while avoiding that recursive call?
Is there a way to remove the need to derive from SQSS3Deserializer for each POJO I want to deserialize this way?
Thanks