Skip to content

Instantly share code, notes, and snippets.

@m-x-k
Created September 26, 2016 20:13
Show Gist options
  • Save m-x-k/e0208e1d6452e2b16d3b5c9651d5f760 to your computer and use it in GitHub Desktop.
Save m-x-k/e0208e1d6452e2b16d3b5c9651d5f760 to your computer and use it in GitHub Desktop.
Spring Boot Application Jackson MixIn Example
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SpringBootApplicationJacksonMixInExample {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplicationJacksonMixInExample.class, args);
}
/*
* TEST: http://localhost:8080
* RESPONSE: { title: "Mr", fullName: "Joe Bloggs" }
*/
@RequestMapping(value = "/")
@ResponseBody
public ResponseEntity<Person> get(){
Person person = new Person("Mr", "Joe Bloggs");
return new ResponseEntity<>(person, HttpStatus.OK);
}
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder b = new Jackson2ObjectMapperBuilder();
b.indentOutput(true).mixIn(Person.class, PersonMixin.class);
return b;
}
public interface PersonMixin {
// Overwrite 'name' with 'fullName' in Json response
@JsonProperty("fullName")
abstract String getName();
}
}
class Person {
private String title;
private String name;
public Person(String title, String name) {
this.title = title;
this.name = name;
}
public String getTitle() {
return title;
}
public String getName() {
return name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment