Web User
Web User

Reputation: 7746

Can Jackson serialize to JSON with customizable key name?

Is it possible to dynamically customize the key names in the JSON response at runtime, rather than creating individual POJO classes for domain level objects?

I am using Spring Boot 1.5.3 with Web Starter, so Jackson dependency is included. I am returning responses in JSON. Typically, I create individual POJO classes, with Jackson annotations if I need to customize key names. For example,

public class Movies {

    private List<String> movies;

    public Movies(List<String> movies) {
        this.movies = movies;
    }

    public List<String> getMovies() {
        return this.movies;
    }

    public void setMovies(List<String> movies) {
        this.movies = movies;
    }
}

When I am returning this from a @RestController with the following code:

@RestController
public class MoviesController {

    @Service
    private MovieService movieService;

    @RequestMapping("/movies/list")
    public ResponseEntity<Movies> getMovies() {
        return new ResponseEntity<Movies>(this.movieService.getMovies(), HttpStatus.OK);
    }
}

I get back a JSON response when invoking this end-point:

{ "movies" : [ "Iron Man", "Spiderman", "The Avengers", "Captain America" ] }

I don't want to be creating the Movies POJO. Instead, I would like to have a generic-typed POJO:

public class GenericResponse {

   @JsonProperty("movies") // <- this needs to be dynamic
   private List<String> data;
   ...
}

...where I can somehow send any key name I want while instantiating GenericResponse as opposed to hard-coding the key name via a @JsonProperty annotation. Is that possible?

Upvotes: 2

Views: 1608

Answers (2)

sumit
sumit

Reputation: 3780

What about doing this through Map ?

public class GenericResponse {
    @JsonValue
    private Map<String, List<String>> data;
  }

and you can use @JsonValue annotation to ignore the "data" field name !

Upvotes: 1

Andreas
Andreas

Reputation: 159185

Replace Movies and GenericResponse with Map<String, List<String>>, then do

map.put("movies", Arrays.asList("Iron Man", "Spiderman", "The Avengers", "Captain America"));

A Map is serialized to JSON as a JSON Object, with the map keys as field names, and map values and field values.

Upvotes: 2

Related Questions