How to handle exceptions in Spring MVC differently for HTML and JSON requests

The ControllerAdvice annotation has an element/attribute called basePackage which can be set to determine which packages it should scan for Controllers and apply the advices. So, what you can do is to separate those Controllers handling normal requests and those handling AJAX requests into different packages then write 2 Exception Handling Controllers with appropriate ControllerAdvice … Read more

dump object to String with Jackson

To serialize with Jackson: public String serialize(Object obj, boolean pretty) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); if (pretty) { return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } return mapper.writeValueAsString(obj); }

@JsonIgnore with @Getter Annotation

To put the @JsonIgnore to the generated getter method, you can use onMethod = @__( @JsonIgnore ). This will generate the getter with the specific annotation. For more details check http://projectlombok.org/features/GetterSetter.html @Getter @Setter public class User { private userName; @Getter(onMethod = @__( @JsonIgnore )) @Setter private password; }

How to access default jackson serialization in a custom serializer

A BeanSerializerModifier will provide you access to the default serialization. Inject a default serializer into the custom serializer public class MyClassSerializer extends JsonSerializer<MyClass> { private final JsonSerializer<Object> defaultSerializer; public MyClassSerializer(JsonSerializer<Object> defaultSerializer) { this.defaultSerializer = checkNotNull(defaultSerializer); } @Override public void serialize(MyClass myclass, JsonGenerator gen, SerializerProvider provider) throws IOException { if (myclass.getSomeProperty() == true) { provider.setAttribute(“special”, true); … Read more

Jackson JSON + Java Generics get LinkedHashMap

The following works and as per StaxMan’s advice no longer uses the deprecated static collectionType() method. public class SoApp { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { System.out.println(“Hello World!”); String s = “[{\”user\”:\”TestCity\”,\”role\”:\”TestCountry\”},{\”user\”:\”TestCity\”,\”role\”:\”TestCountry\”}]”; StringReader sr = new StringReader(“{\”user\”:\”TestCity\”,\”role\”:\”TestCountry\”}”); //UserRole user = mapper.readValue(sr, UserRole.class); mapJsonToObjectList(s,UserRole.class); } protected … Read more

tech