Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@JsonView not working with @RestController [SPR-13331] #17916

Closed
spring-projects-issues opened this issue Aug 7, 2015 · 8 comments
Closed

@JsonView not working with @RestController [SPR-13331] #17916

spring-projects-issues opened this issue Aug 7, 2015 · 8 comments
Assignees
Labels
in: web Issues in web modules (web, webmvc, webflux, websocket) status: invalid An issue that we don't feel is valid

Comments

@spring-projects-issues
Copy link
Collaborator

Fabian Cernota opened SPR-13331 and commented

Hi,

i use Spring 4.1.6 with Jackson 2.5.1 and i want to customize my json output using @jsonview annotation.

I have a Entity Like

@Entity
public class Version{
     @JsonVIew(Views.List.class
     private int id;
     @JsonView(Views.Detail.class)
     private int productId;

//Getter and setters
}

Define my views as follows

public class Views{
   public interface List{
   }

  public interface Detail{
  }
}

JPA Repository:

public interface VersionRepository extends JpaRepository<Version, Long> {

	public Version findById(int versionId);

	@Query(value = "select v from Version v")
	public List<Version> findWithPageable(Pageable pageable);

	public List<Version> findByProdukt_id(int IdProdukt, Pageable pageable);

}

And RestController:

@RestController
@RequestMapping("/versionen")
@Transactional
public class VersionService {
	Logger log = LoggerFactory.getLogger(this.getClass());
	private final ObjectMapper objectMapper = new ObjectMapper();

	@PostConstruct
	public void initialize() {
		log.info("VersionRest Schnittstelle erzeugt");
	}

	@Autowired
	VersionRepository versionRepository;

       @JsonView(Views.List.class)
  	@RequestMapping(method = RequestMethod.GET)
	public Resources<Resource<Version>> getVersionList(@RequestParam(required = false,
			defaultValue = "10")
	final int limit, @RequestParam(required = false, defaultValue = "0")
	final int page, @RequestParam(required = false) Integer produkt) {
		List<Version> versionList;
		if (produkt == null) {

			versionList =
					versionRepository.findWithPageable(new PageRequest(page, limit, Direction.DESC,
							"id"));
		} else {
			versionList =
					versionRepository.findByProdukt_id(produkt, new PageRequest(page, limit,
							Direction.DESC, "id"));
		}
		List<Resource<Version>> versionResourceList = new ArrayList<>();
		for (Version v : versionList) {
			Resource<Version> r = new Resource<>(v);
			r.add(ControllerLinkBuilder.linkTo(
					ControllerLinkBuilder.methodOn(VersionService.class).getVersion(v.getId()))
					.withSelfRel());
			versionResourceList.add(r);
		}

		Resources<Resource<Version>> result = new Resources<>(versionResourceList);
		/**
		 * Letzte Seite berechnen
		 */
		long pageCount = versionRepository.count();
		int lastPage = (int) (pageCount / limit);

		result.add(ControllerLinkBuilder.linkTo(
				ControllerLinkBuilder.methodOn(VersionService.class).getVersionList(limit, 0,
						(produkt == null ? null : produkt))).withRel("first"));
		if (page != 0) {
			result.add(ControllerLinkBuilder.linkTo(
					ControllerLinkBuilder.methodOn(VersionService.class).getVersionList(limit,
							page - 1, (produkt == null ? null : produkt))).withRel("prev"));
		}
		if (page != lastPage) {
			result.add(ControllerLinkBuilder.linkTo(
					ControllerLinkBuilder.methodOn(VersionService.class).getVersionList(limit,
							page + 1, (produkt == null ? null : produkt))).withRel("next"));

		}

		result.add(ControllerLinkBuilder.linkTo(
				ControllerLinkBuilder.methodOn(VersionService.class).getVersionList(limit,
						lastPage, (produkt == null ? null : produkt))).withRel("last"));
		
		return result;

	}

	
}

}

In my browser i only see empty brackets {}. When i doesn't use JSONViews it shows me everything from the entities.

Thanks
Fabian


Affects: 4.1.6

@spring-projects-issues
Copy link
Collaborator Author

Fabian Cernota commented

If there a any questions please ask :)

@spring-projects-issues
Copy link
Collaborator Author

spring-projects-issues commented Aug 7, 2015

Rossen Stoyanchev commented

This is likely related to #17408, which is partly an issue in Jackson (having to do with polymorphic collections) fixed in 2.6 and also required some additional code on the Spring side available in 4.2. If you are able to give it a try with Jackson 2.6 and Spring Framework 4.2 that would be helpful, thanks.

@spring-projects-issues
Copy link
Collaborator Author

Fabian Cernota commented

I still get empty {}

@spring-projects-issues
Copy link
Collaborator Author

spring-projects-issues commented Aug 10, 2015

Sébastien Deleuze commented

If you have empty {}, it may come from what is described in #17154.

Could you have a look to #17154 comments related to setting defaultViewInclusion to true, to this commit that fixed a similar problem in a sample project and to the Jackson documentation about JsonView (when defaultViewInclusion is set to true, non annotated fields are included by default) ?

@spring-projects-issues
Copy link
Collaborator Author

Fabian Cernota commented

I use your example:

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "de.example.project.rest" })
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
	final static Logger log = LoggerFactory.getLogger(WebMvcConfiguration.class);

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().defaultViewInclusion(true).build();
		converters.add(new MappingJackson2HttpMessageConverter(mapper));
		log.info("Jackson Configured");
		log.info(converters.toString());
	}
}

And on the console i get both log lines:

INFO  de.example.project.utils.WebMvcConfiguration - Jackson Configured
INFO  de.example.project.utils.WebMvcConfiguration - [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@5b4e8073]

When i called the REST-service i get Still empty brackets an on console i get a message like

DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Written [org.springframework.http.converter.json.MappingJacksonValue@583a424b] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@39a4125b]

Any ideas?

Thanks

@spring-projects-issues
Copy link
Collaborator Author

Sébastien Deleuze commented

I have tried to reproduce your issue by updating https://github.com/sdeleuze/SpringSampleProject, but it seems to work as expected with Spring 4.1.6 and 4.2.0 (even when returning Resource<Resource<Foo>> like in your example).

Could you provide a small sample project that allows to reproduce the issue?

@spring-projects-issues
Copy link
Collaborator Author

Fabian Cernota commented

Here is a simple Spring sample project were i can reproduce the problem:
https://github.com/FabianCernota/springsample

@spring-projects-issues
Copy link
Collaborator Author

Sébastien Deleuze commented

Thanks for creating a repro project. The root cause of the problem you have is that you have both XML and JavaConfig configuration in your application. defaultViewInclusion is set to true in JavaConfig, but not in XML.

I have created a pull request that fixes your application, but removing the XML based Spring MVC configuration (and other small fixes). With these changes, it seems to work as expected.

@spring-projects-issues spring-projects-issues added type: bug A general bug status: invalid An issue that we don't feel is valid in: web Issues in web modules (web, webmvc, webflux, websocket) labels Jan 11, 2019
@spring-projects-issues spring-projects-issues removed the type: bug A general bug label Jan 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
in: web Issues in web modules (web, webmvc, webflux, websocket) status: invalid An issue that we don't feel is valid
Projects
None yet
Development

No branches or pull requests

2 participants